@vercel/cli-support 66.6.0 → 68.0.0-snapshot-c9dfd83f2293

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 (404) hide show
  1. package/dist/chunks/add-NIIHCHGH.js +8 -0
  2. package/dist/chunks/add-ORZO4EJ7.js +8 -0
  3. package/dist/chunks/add-SKRNSMC6.js +8 -0
  4. package/dist/chunks/{alerts-72Q42HNT.js → alerts-MNMZH6BO.js} +1 -1
  5. package/dist/chunks/build-P7KKWO4O.js +7 -0
  6. package/dist/chunks/{chunk-ZZD5W5KT.js → chunk-23FY4PR3.js} +1 -1
  7. package/dist/chunks/{chunk-YTRKHRL3.js → chunk-27FVSW45.js} +1 -1
  8. package/dist/chunks/{chunk-IIK6GUVI.js → chunk-2BK7SZQA.js} +1 -1
  9. package/dist/chunks/{chunk-WJX5PGNN.js → chunk-2DH6LTUI.js} +1 -1
  10. package/dist/chunks/{chunk-D2TVI7KK.js → chunk-2HFP22IP.js} +4 -4
  11. package/dist/chunks/{chunk-7AVHDJSP.js → chunk-2KXLL3DX.js} +4 -4
  12. package/dist/chunks/{chunk-YEDS2UMW.js → chunk-2ZN4JRDA.js} +1 -1
  13. package/dist/chunks/{chunk-DJZBJC2A.js → chunk-3AFEVHHY.js} +1 -1
  14. package/dist/chunks/{chunk-FOFX7LHS.js → chunk-3OPLG6HM.js} +1 -1
  15. package/dist/chunks/{chunk-Q66LJNIV.js → chunk-3RFQ2NXZ.js} +1 -1
  16. package/dist/chunks/{chunk-F4UEGELU.js → chunk-3VNS4D7V.js} +1 -1
  17. package/dist/chunks/{chunk-XAGG5BJT.js → chunk-43XDA7ST.js} +1 -1
  18. package/dist/chunks/{chunk-OXS5VO4X.js → chunk-4D5DAM3D.js} +1 -1
  19. package/dist/chunks/chunk-4Z6R5KHZ.js +78 -0
  20. package/dist/chunks/{chunk-5KSBRQI2.js → chunk-5727HGA6.js} +1 -1
  21. package/dist/chunks/{chunk-6GE4V7MW.js → chunk-572VGS6P.js} +2 -2
  22. package/dist/chunks/{chunk-O7GNYVVM.js → chunk-5OGPMRRQ.js} +2 -2
  23. package/dist/chunks/{chunk-UUBPAYTG.js → chunk-5RMIM4S2.js} +1 -1
  24. package/dist/chunks/chunk-67GZ5REA.js +7 -0
  25. package/dist/chunks/{chunk-VHSAI6FS.js → chunk-6FEMU5YF.js} +1 -1
  26. package/dist/chunks/chunk-6JTZZSFH.js +7 -0
  27. package/dist/chunks/{chunk-UDZJCD5W.js → chunk-6KNWKZR4.js} +1 -1
  28. package/dist/chunks/{chunk-ZKNEIE44.js → chunk-6NC2JFUQ.js} +1 -1
  29. package/dist/chunks/{chunk-5O4AXCN7.js → chunk-6OJVCMG5.js} +1 -1
  30. package/dist/chunks/{chunk-X7KKWUPS.js → chunk-6WBEU34Y.js} +1 -1
  31. package/dist/chunks/{chunk-NBTFAXL4.js → chunk-6Z5REGCM.js} +1 -1
  32. package/dist/chunks/{chunk-VPSR2O55.js → chunk-7AAYWDIZ.js} +3 -3
  33. package/dist/chunks/{chunk-WIF4VGYZ.js → chunk-7GJ37QPL.js} +1 -1
  34. package/dist/chunks/chunk-7HQZRU25.js +10 -0
  35. package/dist/chunks/{chunk-XECELSF5.js → chunk-7JU5RJ3H.js} +1 -1
  36. package/dist/chunks/{chunk-KSGN5OCV.js → chunk-7K5ZWVDL.js} +1 -1
  37. package/dist/chunks/{chunk-UQZZX2J7.js → chunk-7OZ7OKPS.js} +1 -1
  38. package/dist/chunks/{chunk-PFOOPXTN.js → chunk-7RABG6HV.js} +2 -2
  39. package/dist/chunks/{chunk-AMH5MXDW.js → chunk-7WDSOKOY.js} +1 -1
  40. package/dist/chunks/{chunk-ELM2KPYX.js → chunk-A4LOQ3UK.js} +1 -1
  41. package/dist/chunks/{chunk-SYJXONEV.js → chunk-A6CMQOL7.js} +1 -1
  42. package/dist/chunks/chunk-AOPFMMUK.js +13 -0
  43. package/dist/chunks/{chunk-2OMI3IUW.js → chunk-AVXX4Q6S.js} +1 -1
  44. package/dist/chunks/{chunk-YEUIG3JC.js → chunk-AZVSMIPP.js} +1 -1
  45. package/dist/chunks/{chunk-XLYO5QNG.js → chunk-B7IUFV5P.js} +2 -2
  46. package/dist/chunks/{chunk-IF6GA273.js → chunk-BGIGZUFG.js} +1 -1
  47. package/dist/chunks/{chunk-YLLFLPNA.js → chunk-BHL2HM6I.js} +1 -1
  48. package/dist/chunks/{chunk-YIOMTAUF.js → chunk-BKFRN6C2.js} +1 -1
  49. package/dist/chunks/chunk-BS32OUOC.js +7 -0
  50. package/dist/chunks/{chunk-YJNMDXEG.js → chunk-BUBVZ6SQ.js} +1 -1
  51. package/dist/chunks/{chunk-VZ4URN3U.js → chunk-BYBELFCP.js} +1 -1
  52. package/dist/chunks/{chunk-B7GCRM5I.js → chunk-BYYNR34Q.js} +1 -1
  53. package/dist/chunks/{chunk-5TMHRECT.js → chunk-CAJ2OUSR.js} +1 -1
  54. package/dist/chunks/chunk-CDJ25IKC.js +7 -0
  55. package/dist/chunks/chunk-CJMNUD2I.js +12 -0
  56. package/dist/chunks/chunk-CSNP5RIM.js +11 -0
  57. package/dist/chunks/{chunk-REJLEESP.js → chunk-CTMTO2W4.js} +1 -1
  58. package/dist/chunks/{chunk-K3MGQQEP.js → chunk-D5JQZXL7.js} +1 -1
  59. package/dist/chunks/{chunk-6PDKIOAO.js → chunk-DEFA6XAB.js} +1 -1
  60. package/dist/chunks/{chunk-OE26EQSH.js → chunk-DEX4QU4S.js} +1 -1
  61. package/dist/chunks/{chunk-W2L24GM7.js → chunk-DMA77UYG.js} +1 -1
  62. package/dist/chunks/{chunk-LM3YPF3K.js → chunk-DOOBZO4W.js} +1 -1
  63. package/dist/chunks/chunk-DORCX7UB.js +7 -0
  64. package/dist/chunks/{chunk-C335SWOB.js → chunk-DUSMVY4N.js} +1 -1
  65. package/dist/chunks/{chunk-XDYVJWGX.js → chunk-E5A7E7X6.js} +1 -1
  66. package/dist/chunks/{chunk-GLCSWIB4.js → chunk-E7IN2DGU.js} +1 -1
  67. package/dist/chunks/chunk-EYRBV6RM.js +25 -0
  68. package/dist/chunks/{chunk-AKOYIH3A.js → chunk-F4KY2TOK.js} +1 -1
  69. package/dist/chunks/{chunk-DZ77BIEV.js → chunk-F4ZKTFQH.js} +1 -1
  70. package/dist/chunks/chunk-F7X6O4ZC.js +7 -0
  71. package/dist/chunks/{chunk-TSNRTRIM.js → chunk-FB37TFVF.js} +1 -1
  72. package/dist/chunks/{chunk-BCAI7MED.js → chunk-FGWYM3SF.js} +1 -1
  73. package/dist/chunks/{chunk-SYVWRGFQ.js → chunk-FGXULLNK.js} +1 -1
  74. package/dist/chunks/{chunk-T7GKQYWA.js → chunk-FXLZM6Q7.js} +1 -1
  75. package/dist/chunks/{chunk-JBYROCAC.js → chunk-FYM5EUNW.js} +1 -1
  76. package/dist/chunks/{chunk-RVIJRFVD.js → chunk-G24EKATW.js} +1 -1
  77. package/dist/chunks/chunk-GQXKF3PR.js +7 -0
  78. package/dist/chunks/{chunk-2G2SALNN.js → chunk-H2QMSLKJ.js} +1 -1
  79. package/dist/chunks/{chunk-33HVDSWP.js → chunk-HMJR6RVF.js} +1 -1
  80. package/dist/chunks/{chunk-S4AANAHX.js → chunk-HQ3ZFXXQ.js} +1 -1
  81. package/dist/chunks/chunk-HYGWJQN6.js +8 -0
  82. package/dist/chunks/chunk-I4O53MKV.js +8 -0
  83. package/dist/chunks/{chunk-TOTTVS5P.js → chunk-ID663OJ7.js} +1 -1
  84. package/dist/chunks/{chunk-FFN3EGSF.js → chunk-IKNAOU5O.js} +1 -1
  85. package/dist/chunks/{chunk-CINNNQDJ.js → chunk-INIZJZ3O.js} +1 -1
  86. package/dist/chunks/{chunk-LNZEYUEC.js → chunk-IVZNPSHU.js} +1 -1
  87. package/dist/chunks/{chunk-YOAQNRBN.js → chunk-IY7OKDHU.js} +3 -3
  88. package/dist/chunks/{chunk-2D5PTFAY.js → chunk-J7POLUHY.js} +1 -1
  89. package/dist/chunks/{chunk-6CJFPT4F.js → chunk-JDDPCL3K.js} +1 -1
  90. package/dist/chunks/chunk-JR25PLC7.js +13 -0
  91. package/dist/chunks/chunk-JV3YIOCO.js +7 -0
  92. package/dist/chunks/{chunk-RBW62SOU.js → chunk-JXE7GYE3.js} +1 -1
  93. package/dist/chunks/{chunk-EFP3LK4G.js → chunk-K5SM5NIY.js} +1 -1
  94. package/dist/chunks/chunk-K6KS5GZD.js +16 -0
  95. package/dist/chunks/chunk-K7TSWIKR.js +12 -0
  96. package/dist/chunks/{chunk-FEJD7MRH.js → chunk-KA2KG3SY.js} +1 -1
  97. package/dist/chunks/{chunk-GUGP6OY2.js → chunk-KFBA2MAV.js} +1 -1
  98. package/dist/chunks/{table-W6LOHWWF.js → chunk-KG526MHL.js} +1 -1
  99. package/dist/chunks/chunk-KHMNANEN.js +7 -0
  100. package/dist/chunks/chunk-KVXEYKIX.js +7 -0
  101. package/dist/chunks/{chunk-F37XFLFP.js → chunk-L3YEI2RW.js} +1 -1
  102. package/dist/chunks/{chunk-54FY6GJ5.js → chunk-L46V6VL3.js} +1 -1
  103. package/dist/chunks/chunk-LD25KYMI.js +30 -0
  104. package/dist/chunks/{chunk-ANIA2G6F.js → chunk-LDDXXDN5.js} +1 -1
  105. package/dist/chunks/{chunk-M7FED5YP.js → chunk-M2Q2DUHO.js} +1 -1
  106. package/dist/chunks/{chunk-5ZCSFPWG.js → chunk-MDRI27KN.js} +1 -1
  107. package/dist/chunks/{chunk-2AU6O6Z5.js → chunk-MJ77FDK2.js} +1 -1
  108. package/dist/chunks/{chunk-GHNHUSVK.js → chunk-MMMJO2M3.js} +1 -1
  109. package/dist/chunks/chunk-N4PID4SD.js +7 -0
  110. package/dist/chunks/chunk-N6MNUNZ4.js +37 -0
  111. package/dist/chunks/chunk-NMY2YZ6M.js +8 -0
  112. package/dist/chunks/{chunk-QRG24GJG.js → chunk-NOAZDAOU.js} +1 -1
  113. package/dist/chunks/{chunk-ZJNDLFZ7.js → chunk-OOPF73RV.js} +1 -1
  114. package/dist/chunks/{chunk-YRKW42CD.js → chunk-OQXHBPPS.js} +1 -1
  115. package/dist/chunks/{chunk-SQCVI2EG.js → chunk-OVWS4CFW.js} +1 -1
  116. package/dist/chunks/{chunk-WAFBTC45.js → chunk-PHPJS2G2.js} +1 -1
  117. package/dist/chunks/{chunk-TNQUCTJH.js → chunk-PPCZYUSO.js} +1 -1
  118. package/dist/chunks/chunk-PZL7NSDA.js +24 -0
  119. package/dist/chunks/{chunk-OISNKAC6.js → chunk-Q45SQL44.js} +2 -2
  120. package/dist/chunks/{chunk-XDWAUOFO.js → chunk-Q4XCBBWK.js} +1 -1
  121. package/dist/chunks/chunk-Q7HFUXJ4.js +10 -0
  122. package/dist/chunks/chunk-QFE3RPMA.js +19 -0
  123. package/dist/chunks/{chunk-L5PIUIUM.js → chunk-QFSIUMC6.js} +1 -1
  124. package/dist/chunks/{chunk-CSCUVSJM.js → chunk-QG5UBKDA.js} +1 -1
  125. package/dist/chunks/{chunk-KLYFOXYH.js → chunk-QGS3ERDZ.js} +3 -3
  126. package/dist/chunks/{chunk-3UZE566G.js → chunk-QSL6AG2B.js} +1 -1
  127. package/dist/chunks/chunk-QU74BFN2.js +10 -0
  128. package/dist/chunks/{chunk-ACN6DBTC.js → chunk-R3QHEJL6.js} +1 -1
  129. package/dist/chunks/{chunk-BDXK4TCN.js → chunk-RHFNVIFD.js} +1 -1
  130. package/dist/chunks/chunk-RPYIWRSN.js +7 -0
  131. package/dist/chunks/{chunk-AP6DZGTK.js → chunk-RYSO5U3E.js} +1 -1
  132. package/dist/chunks/{chunk-N6JHFCWC.js → chunk-S7Y24A5X.js} +1 -1
  133. package/dist/chunks/chunk-SGNDE4YS.js +7 -0
  134. package/dist/chunks/{chunk-OF32Z3UP.js → chunk-SHJ3XTD3.js} +1 -1
  135. package/dist/chunks/{chunk-R33HJGYA.js → chunk-SHL6BPBV.js} +1 -1
  136. package/dist/chunks/{chunk-GLIQ4KNY.js → chunk-SQ62IODX.js} +1 -1
  137. package/dist/chunks/{chunk-PIDEH4SJ.js → chunk-T44RB754.js} +1 -1
  138. package/dist/chunks/{chunk-DHKWTBF6.js → chunk-T4DOV5S4.js} +1 -1
  139. package/dist/chunks/chunk-T5JHWXS5.js +8 -0
  140. package/dist/chunks/{chunk-TJUZVODP.js → chunk-TLKBGAOL.js} +1 -1
  141. package/dist/chunks/{chunk-ZA5O22ZY.js → chunk-TOCPUQ6N.js} +1 -1
  142. package/dist/chunks/{chunk-CJZE7647.js → chunk-U5SZQUYO.js} +1 -1
  143. package/dist/chunks/chunk-UAS3WUFB.js +11 -0
  144. package/dist/chunks/chunk-VIOIR6II.js +7 -0
  145. package/dist/chunks/{chunk-3A3GU62R.js → chunk-VMRFCU6F.js} +1 -1
  146. package/dist/chunks/{chunk-Y77DXGGN.js → chunk-VQZ773A2.js} +1 -1
  147. package/dist/chunks/chunk-VWKA6RKB.js +7 -0
  148. package/dist/chunks/{chunk-FCTTEFC5.js → chunk-WAOS5OCB.js} +1 -1
  149. package/dist/chunks/chunk-WBEPIG4S.js +31 -0
  150. package/dist/chunks/{chunk-AFHZC47H.js → chunk-WBXM3W44.js} +1 -1
  151. package/dist/chunks/{chunk-MINTHN6C.js → chunk-WEL2Y6OH.js} +1 -1
  152. package/dist/chunks/{chunk-RDDIWY3O.js → chunk-WGU2IQPY.js} +3 -3
  153. package/dist/chunks/{chunk-DOMBKOLJ.js → chunk-WLD4SGKM.js} +1 -1
  154. package/dist/chunks/{chunk-6FYPSSL4.js → chunk-X6JQI64G.js} +1 -1
  155. package/dist/chunks/{chunk-L75A5BMY.js → chunk-X755TPX6.js} +1 -1
  156. package/dist/chunks/{chunk-QZKRVE44.js → chunk-XQZBXQZ2.js} +1 -1
  157. package/dist/chunks/{chunk-AB4WXRCO.js → chunk-Y3V4JYK6.js} +1 -1
  158. package/dist/chunks/{chunk-LKW6GVP2.js → chunk-Y4YBQUQM.js} +1 -1
  159. package/dist/chunks/{chunk-I5KIA2XV.js → chunk-YBAGKQXC.js} +1 -1
  160. package/dist/chunks/{chunk-3OZCZF4N.js → chunk-YFOBGEOW.js} +1 -1
  161. package/dist/chunks/{chunk-E4VPDMRQ.js → chunk-YJJCELMY.js} +1 -1
  162. package/dist/chunks/chunk-YLXXGQQQ.js +7 -0
  163. package/dist/chunks/{chunk-BMIYC2MH.js → chunk-YN3HZJXW.js} +1 -1
  164. package/dist/chunks/chunk-YNMTP26U.js +7 -0
  165. package/dist/chunks/chunk-YTSGFU5T.js +7 -0
  166. package/dist/chunks/{chunk-Z2PTPD6J.js → chunk-YTSUDTAK.js} +1 -1
  167. package/dist/chunks/{chunk-QZJOKECY.js → chunk-YYDI5Q5K.js} +2 -2
  168. package/dist/chunks/{chunk-DOBV3XLO.js → chunk-Z3YQZSU4.js} +1 -1
  169. package/dist/chunks/chunk-Z643WTC4.js +15 -0
  170. package/dist/chunks/{chunk-D2E4COIY.js → chunk-ZBZQEDZY.js} +1 -1
  171. package/dist/chunks/chunk-ZRFDZO7Y.js +7 -0
  172. package/dist/chunks/chunk-ZSEFELXB.js +23 -0
  173. package/dist/chunks/{chunk-UECFEOOH.js → chunk-ZXSZH7N5.js} +1 -1
  174. package/dist/chunks/clear-B3I7ZYEY.js +8 -0
  175. package/dist/chunks/cli-embedded-NR5F35LW.js +87 -0
  176. package/dist/chunks/compile-vercel-config-ZQMPTEM6.js +7 -0
  177. package/dist/chunks/config-4GZY5MR4.js +7 -0
  178. package/dist/chunks/config-ZY22VRFX.js +8 -0
  179. package/dist/chunks/config-validator.mjs +1 -1
  180. package/dist/chunks/{connect-git-provider-CIRRFPI2.js → connect-git-provider-WGKVFXW2.js} +1 -1
  181. package/dist/chunks/create-project-BTOHPKZB.js +7 -0
  182. package/dist/chunks/delete-K2HS7YCM.js +10 -0
  183. package/dist/chunks/delete-RVTGE4BU.js +9 -0
  184. package/dist/chunks/describe-5ZCOXUID.js +25 -0
  185. package/dist/chunks/detect-projects-AZXG6BRD.js +7 -0
  186. package/dist/chunks/detect-services-FLNYWWJS.js +7 -0
  187. package/dist/chunks/disable-AS6DQMHM.js +7 -0
  188. package/dist/chunks/discard-PYU5CG67.js +14 -0
  189. package/dist/chunks/edit-HSMIPVPN.js +9 -0
  190. package/dist/chunks/edit-RLRJSNZY.js +8 -0
  191. package/dist/chunks/enable-JPWR5EPC.js +7 -0
  192. package/dist/chunks/{engine-D8YAsQS_-WNPHYRQF.js → engine-C8wCzkw--PYVABGU4.js} +1 -1
  193. package/dist/chunks/esm-5GQXHN7C.js +9 -0
  194. package/dist/chunks/esm-FJCIOBBV.js +7 -0
  195. package/dist/chunks/{esm-FSME24KA.js → esm-IYH32MTQ.js} +1 -1
  196. package/dist/chunks/esm-LEQXRLFV.js +9 -0
  197. package/dist/chunks/esm-NHCCFW7Z.js +7 -0
  198. package/dist/chunks/esm-QQ3MUOW4.js +7 -0
  199. package/dist/chunks/esm-T655CG6O.js +7 -0
  200. package/dist/chunks/{exec-ALB7WFEF.js → exec-PCSP64LR.js} +1 -1
  201. package/dist/chunks/{export-TOSUN6JO.js → export-6WFWSAO4.js} +2 -3
  202. package/dist/chunks/future-QLQMHIPL.js +7 -0
  203. package/dist/chunks/generate-cert-for-deploy-JKVOVQ3B.js +7 -0
  204. package/dist/chunks/image-POIJ2G2Y.js +7 -0
  205. package/dist/chunks/import-builders-YF5MX6ZA.js +7 -0
  206. package/dist/chunks/{inspect-SX3QQUEQ.js → inspect-4CURZZPU.js} +1 -1
  207. package/dist/chunks/{inspect-DFYVVIJW.js → inspect-BAYMK22S.js} +1 -1
  208. package/dist/chunks/inspect-JTBMNWWI.js +13 -0
  209. package/dist/chunks/{inspect-GBH7FAW6.js → inspect-TBQRBTX3.js} +1 -1
  210. package/dist/chunks/inspect-W4WSFBOF.js +9 -0
  211. package/dist/chunks/{inspect-4Y2OD5MI.js → inspect-YKSWSH3T.js} +1 -1
  212. package/dist/chunks/{list-HD6KXAIG.js → list-E65OFWSS.js} +1 -1
  213. package/dist/chunks/list-EWYN3F4Y.js +12 -0
  214. package/dist/chunks/{list-MW2FV253.js → list-ZHES2WYK.js} +1 -1
  215. package/dist/chunks/{list-4RRL326Z.js → list-ZWJDFJNY.js} +1 -1
  216. package/dist/chunks/login-JAKNSTW3.js +9 -0
  217. package/dist/chunks/login-JRGX6HGZ.js +7 -0
  218. package/dist/chunks/logs-3DPLX3CB.js +7 -0
  219. package/dist/chunks/{ls-VFE7PE25.js → ls-5YLM3ICH.js} +1 -1
  220. package/dist/chunks/ls-6HPMZVYA.js +11 -0
  221. package/dist/chunks/{ls-RKOM46KV.js → ls-FWOTN6V6.js} +1 -1
  222. package/dist/chunks/{ls-I767MTW4.js → ls-MW3WIHH5.js} +1 -1
  223. package/dist/chunks/{ls-Q4WGEEBZ.js → ls-RAVFLQTQ.js} +1 -1
  224. package/dist/chunks/ls-SY2FW3WA.js +8 -0
  225. package/dist/chunks/{ls-TLEAYYXQ.js → ls-ZX5FNEK2.js} +1 -1
  226. package/dist/chunks/migrate-experimental-services-XYUCY2G6.js +7 -0
  227. package/dist/chunks/mutate-4KTZMM3X.js +9 -0
  228. package/dist/chunks/{native-self-update-JDTL3IBF.js → native-self-update-Q3EN6NZK.js} +1 -1
  229. package/dist/chunks/notifications-LBZ7KWGS.js +7 -0
  230. package/dist/chunks/open-PXLVSFII.js +7 -0
  231. package/dist/chunks/{openapi-NEYEIRF2.js → openapi-6RKKA6JG.js} +1 -1
  232. package/dist/chunks/permissions-DQ5AF6XL.js +7 -0
  233. package/dist/chunks/{plugin-offer-NPJAEILN.js → plugin-offer-VU3R572E.js} +1 -1
  234. package/dist/chunks/prompt-missing-credentials-AJH3HM36.js +7 -0
  235. package/dist/chunks/publish-QJJL3IHG.js +15 -0
  236. package/dist/chunks/pull-3PQHXMPB.js +7 -0
  237. package/dist/chunks/purchase-domain-if-available-IFCQ4QFP.js +7 -0
  238. package/dist/chunks/push-4VIQFKP3.js +7 -0
  239. package/dist/chunks/query-BQ4HYVQ7.js +7 -0
  240. package/dist/chunks/raw-query-VA6VVMR4.js +8 -0
  241. package/dist/chunks/reauthenticate-2SMCQQHF.js +7 -0
  242. package/dist/chunks/{remove-IEEZGRB2.js → remove-CSIMGLLS.js} +1 -1
  243. package/dist/chunks/reorder-ERRB7OJL.js +10 -0
  244. package/dist/chunks/reply-XCBWXFWS.js +9 -0
  245. package/dist/chunks/repo-root-DZ6WFHMP.js +7 -0
  246. package/dist/chunks/resolve-VWGZ632M.js +12 -0
  247. package/dist/chunks/resolve-agent-team-NWELD5FN.js +7 -0
  248. package/dist/chunks/{resolve-deployment-framework-preset-4TKUU6AH.js → resolve-deployment-framework-preset-BLMQLCIN.js} +1 -1
  249. package/dist/chunks/restore-SXZUZGZE.js +16 -0
  250. package/dist/chunks/rm-5TRC5YND.js +8 -0
  251. package/dist/chunks/rm-IQ33QTQ2.js +8 -0
  252. package/dist/chunks/rm-KURYLLD6.js +8 -0
  253. package/dist/chunks/rm-WCE3ISB2.js +8 -0
  254. package/dist/chunks/rm-XMWM76JA.js +8 -0
  255. package/dist/chunks/routes-SBMN6SDF.js +7 -0
  256. package/dist/chunks/rule-inspect-USW6K7Y7.js +8 -0
  257. package/dist/chunks/schema-2G5VJ7EY.js +14 -0
  258. package/dist/chunks/{schema-L5VCG6FJ.js → schema-LRRKG2KJ.js} +1 -1
  259. package/dist/chunks/select-org-JG6GRWTS.js +7 -0
  260. package/dist/chunks/{serving-aOQsBok0-OL36TMZU.js → serving-C1mhZQqH-73TMEGEB.js} +1 -1
  261. package/dist/chunks/set-4JTH62JO.js +7 -0
  262. package/dist/chunks/{set-6U4QIX7A.js → set-BS5KCRE4.js} +1 -1
  263. package/dist/chunks/setup-and-link-GY4O7UJP.js +7 -0
  264. package/dist/chunks/{skills-ZMFZGPQL.js → skills-SUGA6D3G.js} +4 -19
  265. package/dist/chunks/table-SCLK33K7.js +7 -0
  266. package/dist/chunks/tags-B7MKMQKJ.js +7 -0
  267. package/dist/chunks/{types-CVLZCTL2.js → types-YFDB4QZA.js} +1 -1
  268. package/dist/chunks/{update-A727QN7H.js → update-LWRCCEXG.js} +1 -1
  269. package/dist/chunks/usage-HABW5VJ7.js +15 -0
  270. package/dist/chunks/validate-config-LDOYJ4LL.js +7 -0
  271. package/dist/commands/build/index.js +1 -1
  272. package/dist/commands/deploy/index.js +28 -25
  273. package/dist/commands/dev/index.js +7 -7
  274. package/dist/commands/env/index.js +12 -11
  275. package/dist/commands/link/index.js +3 -3
  276. package/dist/commands/list/index.js +1 -1
  277. package/dist/commands/project/index.js +4 -4
  278. package/dist/commands/tunnel/index.js +1 -1
  279. package/dist/commands-account.js +18 -12
  280. package/dist/commands-ai.js +18 -11
  281. package/dist/commands-blob.js +6 -6
  282. package/dist/commands-core.js +34 -48
  283. package/dist/commands-deployments.js +12 -11
  284. package/dist/commands-flags.js +27 -22
  285. package/dist/commands-integrations.js +7 -10
  286. package/dist/commands-observability.js +38 -28
  287. package/dist/commands-routing.js +6 -7
  288. package/dist/help.js +1 -1
  289. package/dist/index.js +6 -6
  290. package/dist/internal-build-worker.js +1 -1
  291. package/dist/internal-build.js +1 -1
  292. package/dist/package.json +43 -43
  293. package/dist/version.mjs +1 -1
  294. package/package.json +44 -44
  295. package/dist/chunks/add-563RV6JX.js +0 -8
  296. package/dist/chunks/add-HRB6XY33.js +0 -8
  297. package/dist/chunks/add-IUTGTBA4.js +0 -8
  298. package/dist/chunks/build-OMIYCGMR.js +0 -7
  299. package/dist/chunks/chunk-2GBU6ULJ.js +0 -7
  300. package/dist/chunks/chunk-2RRZCRWX.js +0 -7
  301. package/dist/chunks/chunk-4SS6W6JK.js +0 -11
  302. package/dist/chunks/chunk-5J4E2W4F.js +0 -12
  303. package/dist/chunks/chunk-76DSBD4X.js +0 -7
  304. package/dist/chunks/chunk-7W565DJB.js +0 -8
  305. package/dist/chunks/chunk-AIXEVICT.js +0 -37
  306. package/dist/chunks/chunk-AM46JVVN.js +0 -7
  307. package/dist/chunks/chunk-BULSRTQE.js +0 -7
  308. package/dist/chunks/chunk-C35SG42R.js +0 -7
  309. package/dist/chunks/chunk-CFJBDBYH.js +0 -7
  310. package/dist/chunks/chunk-DDPH26ZO.js +0 -7
  311. package/dist/chunks/chunk-EAQAV7UZ.js +0 -8
  312. package/dist/chunks/chunk-EFFJUYYS.js +0 -31
  313. package/dist/chunks/chunk-GOI2VVI7.js +0 -19
  314. package/dist/chunks/chunk-GYUNOFDD.js +0 -10
  315. package/dist/chunks/chunk-H2KNSYPR.js +0 -16
  316. package/dist/chunks/chunk-KDCODXVL.js +0 -25
  317. package/dist/chunks/chunk-KMTHGHJV.js +0 -8
  318. package/dist/chunks/chunk-KQ6X77WP.js +0 -7
  319. package/dist/chunks/chunk-KRP4EMD2.js +0 -10
  320. package/dist/chunks/chunk-NLK7NGVP.js +0 -7
  321. package/dist/chunks/chunk-OCR5CRTH.js +0 -10
  322. package/dist/chunks/chunk-PKR32I2N.js +0 -30
  323. package/dist/chunks/chunk-QGHAD5A5.js +0 -12
  324. package/dist/chunks/chunk-SPVOJ3HW.js +0 -7
  325. package/dist/chunks/chunk-SXW2G4WD.js +0 -10
  326. package/dist/chunks/chunk-TC4E2TFA.js +0 -8
  327. package/dist/chunks/chunk-TUB3APDV.js +0 -7
  328. package/dist/chunks/chunk-UG3FZ5Q7.js +0 -7
  329. package/dist/chunks/chunk-VF7XWPXA.js +0 -7
  330. package/dist/chunks/chunk-VKVH7LHB.js +0 -7
  331. package/dist/chunks/chunk-VUUU4KDL.js +0 -7
  332. package/dist/chunks/chunk-W3ZH27MN.js +0 -13
  333. package/dist/chunks/chunk-X47GV5HM.js +0 -15
  334. package/dist/chunks/chunk-XBHAU2M3.js +0 -9
  335. package/dist/chunks/chunk-XR2J7PQN.js +0 -12
  336. package/dist/chunks/chunk-YI7NKOCU.js +0 -23
  337. package/dist/chunks/chunk-Z2KANBOU.js +0 -69
  338. package/dist/chunks/chunk-Z7WZVEPP.js +0 -7
  339. package/dist/chunks/clear-TH6G33QK.js +0 -8
  340. package/dist/chunks/cli-embedded-FD3CAPRY.js +0 -84
  341. package/dist/chunks/compile-vercel-config-24IXPM4W.js +0 -7
  342. package/dist/chunks/config-2SBML7OY.js +0 -8
  343. package/dist/chunks/config-BCKJNJPS.js +0 -7
  344. package/dist/chunks/create-project-I7UXVWIR.js +0 -7
  345. package/dist/chunks/delete-RGHXL4JH.js +0 -9
  346. package/dist/chunks/delete-ZV4SHUTR.js +0 -10
  347. package/dist/chunks/describe-442UUQIF.js +0 -25
  348. package/dist/chunks/detect-projects-NBZSMQ5C.js +0 -7
  349. package/dist/chunks/detect-services-CRZW6FKM.js +0 -7
  350. package/dist/chunks/disable-MYGA6HVS.js +0 -7
  351. package/dist/chunks/discard-I5TKYCDJ.js +0 -14
  352. package/dist/chunks/edit-KGCUTTOZ.js +0 -8
  353. package/dist/chunks/edit-ZRNGGRVL.js +0 -9
  354. package/dist/chunks/enable-NODSFDKF.js +0 -7
  355. package/dist/chunks/esm-CF5UHWPM.js +0 -7
  356. package/dist/chunks/esm-EYOXGOVF.js +0 -7
  357. package/dist/chunks/esm-IUATPKKB.js +0 -9
  358. package/dist/chunks/esm-L6OKDFWP.js +0 -7
  359. package/dist/chunks/esm-ORQC2ZSA.js +0 -7
  360. package/dist/chunks/esm-PYIZNQIK.js +0 -9
  361. package/dist/chunks/future-RXI2OW2C.js +0 -7
  362. package/dist/chunks/generate-cert-for-deploy-7BX47IPD.js +0 -7
  363. package/dist/chunks/image-6A2EJP4N.js +0 -7
  364. package/dist/chunks/import-builders-I4JB6BA6.js +0 -7
  365. package/dist/chunks/inspect-STKCC3MC.js +0 -9
  366. package/dist/chunks/inspect-VFUV7BDM.js +0 -13
  367. package/dist/chunks/list-6ENV2ZGG.js +0 -12
  368. package/dist/chunks/login-O6NLJ42W.js +0 -7
  369. package/dist/chunks/login-U5VDJURN.js +0 -9
  370. package/dist/chunks/logs-X3KGHA3J.js +0 -7
  371. package/dist/chunks/ls-HRSD6VNW.js +0 -8
  372. package/dist/chunks/ls-OLJMGFTV.js +0 -11
  373. package/dist/chunks/migrate-experimental-services-7ZYHE5WA.js +0 -7
  374. package/dist/chunks/mutate-BJXJON5E.js +0 -9
  375. package/dist/chunks/notifications-F3NRNUHQ.js +0 -7
  376. package/dist/chunks/open-JK42ZTLB.js +0 -7
  377. package/dist/chunks/permissions-3AQO3DCH.js +0 -7
  378. package/dist/chunks/prompt-missing-credentials-AHAH27TZ.js +0 -7
  379. package/dist/chunks/publish-7SCXBVZR.js +0 -15
  380. package/dist/chunks/pull-LAPD5XJG.js +0 -7
  381. package/dist/chunks/purchase-domain-if-available-7MI52MFD.js +0 -7
  382. package/dist/chunks/push-BCSGQBAM.js +0 -7
  383. package/dist/chunks/query-U72BDMAK.js +0 -7
  384. package/dist/chunks/raw-query-4UAW7M5Q.js +0 -8
  385. package/dist/chunks/reauthenticate-HGOLSK2M.js +0 -7
  386. package/dist/chunks/reorder-YL6L6IWC.js +0 -10
  387. package/dist/chunks/reply-7Y5TN5UV.js +0 -9
  388. package/dist/chunks/resolve-C62436YM.js +0 -12
  389. package/dist/chunks/resolve-agent-team-SR3ALPCH.js +0 -7
  390. package/dist/chunks/restore-Z63JM5CN.js +0 -16
  391. package/dist/chunks/rm-C6QSHEA2.js +0 -8
  392. package/dist/chunks/rm-DDKE62T7.js +0 -8
  393. package/dist/chunks/rm-IUB55CCM.js +0 -8
  394. package/dist/chunks/rm-NZX43GMQ.js +0 -8
  395. package/dist/chunks/rm-UBUI7JNY.js +0 -8
  396. package/dist/chunks/routes-TME3VYIF.js +0 -7
  397. package/dist/chunks/rule-inspect-KF4BLH4K.js +0 -8
  398. package/dist/chunks/schema-P7DFLXCG.js +0 -14
  399. package/dist/chunks/select-org-MBBMOUK2.js +0 -7
  400. package/dist/chunks/set-SCKMJ7LZ.js +0 -7
  401. package/dist/chunks/setup-and-link-5TPDTJIN.js +0 -7
  402. package/dist/chunks/tags-7M2EW6LU.js +0 -7
  403. package/dist/chunks/usage-HT5JXVAA.js +0 -13
  404. package/dist/chunks/validate-config-Q77XESW5.js +0 -7
@@ -4,7 +4,7 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{init_dist,parse as parse2,stringify}from"./chunk-U4Z2MMOF.js";import{applyEdits,init_main,modify,parse,printParseErrorCode}from"./chunk-J24BABG4.js";import{require_execa}from"./chunk-M32HBBPK.js";import{external_exports}from"./chunk-2AMO2VMV.js";import{printAlignedLabel}from"./chunk-M7FED5YP.js";import{output_manager_default}from"./chunk-AP6DZGTK.js";import{__toESM}from"./chunk-BZENIQ7N.js";import{join as join2}from"node:path";init_dist();init_main();import{readFile,writeFile,mkdir,copyFile,access,chmod,lstat,stat,link,unlink}from"node:fs/promises";import{isDeepStrictEqual}from"node:util";import{dirname}from"node:path";async function pathExists(path){try{return await access(path),!0}catch{return!1}}async function isFile(path){try{return(await stat(path)).isFile()}catch{return!1}}async function isSymlink(path){try{return(await lstat(path)).isSymbolicLink()}catch{return!1}}async function readFileOrNull(path){try{return await readFile(path,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Object.getPrototypeOf(value)===Object.prototype}function deepMerge(base,patch){let out={...base};for(let[key,patchValue]of Object.entries(patch)){let baseValue=out[key];isPlainObject(baseValue)&&isPlainObject(patchValue)?out[key]=deepMerge(baseValue,patchValue):out[key]=patchValue}return out}function detectJsonFormatting(text){let eol=text.includes(`\r
7
+ import{init_dist,parse as parse2,stringify}from"./chunk-U4Z2MMOF.js";import{applyEdits,init_main,modify,parse,printParseErrorCode}from"./chunk-J24BABG4.js";import{require_execa}from"./chunk-M32HBBPK.js";import{external_exports}from"./chunk-2AMO2VMV.js";import{printAlignedLabel}from"./chunk-M2Q2DUHO.js";import{require_lib}from"./chunk-LUX4PBJL.js";import{output_manager_default}from"./chunk-RYSO5U3E.js";import{__toESM}from"./chunk-BZENIQ7N.js";import{join as join2}from"node:path";init_dist();init_main();import{readFile,writeFile,mkdir,copyFile,access,chmod,lstat,stat,link,unlink}from"node:fs/promises";import{isDeepStrictEqual}from"node:util";import{dirname}from"node:path";async function pathExists(path){try{return await access(path),!0}catch{return!1}}async function isFile(path){try{return(await stat(path)).isFile()}catch{return!1}}async function isSymlink(path){try{return(await lstat(path)).isSymbolicLink()}catch{return!1}}async function readFileOrNull(path){try{return await readFile(path,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Object.getPrototypeOf(value)===Object.prototype}function deepMerge(base,patch){let out={...base};for(let[key,patchValue]of Object.entries(patch)){let baseValue=out[key];isPlainObject(baseValue)&&isPlainObject(patchValue)?out[key]=deepMerge(baseValue,patchValue):out[key]=patchValue}return out}function detectJsonFormatting(text){let eol=text.includes(`\r
8
8
  `)?`\r
9
9
  `:`
10
10
  `,indent=text.match(/^([ \t]+)\S/m)?.[1];return indent?.startsWith(" ")?{eol,insertSpaces:!1,tabSize:1}:{eol,insertSpaces:!0,tabSize:indent?.length||2}}function parseJsonObjectOrNull(current,parse4=JSON.parse){if(!current||!current.trim())return null;let raw;try{raw=parse4(current)}catch(err){throw new Error(`existing file is not valid JSON (${err.message})`)}if(!isPlainObject(raw))throw new Error("existing file is not a JSON object");return raw}function mergeJson(current,patch,parse4=JSON.parse){let raw=parseJsonObjectOrNull(current,parse4);if(!current||raw===null)return`${JSON.stringify(deepMerge({},patch),null,2)}
@@ -27,7 +27,7 @@ ${MANAGED_BLOCK_END}`,existing=current??"",start=existing.indexOf(MANAGED_BLOCK_
27
27
  `}async function publishNoClobber(temporary,destination){try{return await link(temporary,destination),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}finally{await unlink(temporary).catch(()=>{})}}async function ensureMode(path,mode){try{await chmod(path,mode)}catch{}}async function backupFile(path,mode){let backupPath=`${path}.bak`;return mode===void 0?(await copyFile(path,backupPath),backupPath):(await ensureMode(backupPath,mode),await writeFile(backupPath,await readFile(path,"utf8"),{mode}),backupPath)}async function writeConfigFile(path,content,mode){await mkdir(dirname(path),{recursive:!0}),mode!==void 0&&await ensureMode(path,mode),await writeFile(path,content,mode===void 0?"utf8":{mode})}var GATEWAY_ANTHROPIC_BASE_URL="https://ai-gateway.vercel.sh",GATEWAY_CODING_AGENT_BASE_URL="https://ai-gateway.vercel.sh/coding-agent/v1",GATEWAY_CURSOR_BASE_URL="https://ai-gateway.vercel.sh/cursor/v1",GATEWAY_CODEX_BASE_URL="https://ai-gateway.vercel.sh/codex/v1",GATEWAY_CLAUDE_CODE_BASE_URL="https://ai-gateway.vercel.sh/claude-code",GATEWAY_API_KEY_ENV="AI_GATEWAY_API_KEY",GATEWAY_DEFAULT_MODEL="anthropic/claude-fable-5",KEY_PLACEHOLDER="__AI_GATEWAY_API_KEY__";function resolveGatewayBaseUrl(override,agentDefault){let trimmed=override?.trim();return trimmed||agentDefault}function maskSecret(secret){return secret&&(secret===KEY_PLACEHOLDER||secret.length<=8?"\u2022\u2022\u2022\u2022":`${secret.slice(0,4)}\u2022\u2022\u2022\u2022${secret.slice(-4)}`)}import{randomUUID}from"node:crypto";import*as fs from"node:fs/promises";import{dirname as dirname2,join}from"node:path";var MAX_RECORD_BYTES=1024*1024;function codeSpan(value){return`\`${value.replace(/[`\r\n]/g,"")}\``}var RECORD_PATTERN=/\.json$/;function claudeAppSupportRoot(home){return process.platform==="darwin"?join(home,"Library","Application Support"):process.platform==="win32"?process.env.APPDATA||join(home,"AppData","Roaming"):join(home,".config")}function toGatewayModelId(model){return model.includes("/")?model:`anthropic/${model}`}async function listSubdirectories(path){try{return(await fs.readdir(path,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function findDestinationIdentity(root){let best=null;for(let account of await listSubdirectories(root))for(let org of await listSubdirectories(join(root,account))){let path=join(root,account,org);try{let stat4=await fs.stat(path);(!best||stat4.mtimeMs>best.mtime)&&(best={path,mtime:stat4.mtimeMs})}catch{}}return best?.path??null}async function readRecord(path){let stat4;try{stat4=await fs.stat(path)}catch{return null}if(!stat4.isFile()||stat4.size>MAX_RECORD_BYTES)return null;try{let raw=await fs.readFile(path,"utf8"),record=JSON.parse(raw);return typeof record!="object"||record===null||Array.isArray(record)?null:{record,bytes:stat4.size}}catch{return null}}async function writeRecordNoClobber(destination,contents){if(await pathExists(destination))return"skipped";await fs.mkdir(dirname2(destination),{recursive:!0});let temp=join(dirname2(destination),`.migrate-${randomUUID()}.tmp`);return await fs.writeFile(temp,contents,{mode:384}),await publishNoClobber(temp,destination)?"copied":"skipped"}async function planClaudeDesktopSessionMigration(home,appSupportRoot=claudeAppSupportRoot(home)){let subscriptionRoot=join(appSupportRoot,"Claude","claude-code-sessions"),gatewayRoot=join(appSupportRoot,"Claude-3p","claude-code-sessions"),destinationDir=await findDestinationIdentity(gatewayRoot);if(!destinationDir)return null;let copies=[],totalBytes=0;for(let account of await listSubdirectories(subscriptionRoot))for(let org of await listSubdirectories(join(subscriptionRoot,account))){let identityDir=join(subscriptionRoot,account,org),names;try{names=await fs.readdir(identityDir)}catch{continue}for(let name of names){if(!RECORD_PATTERN.test(name))continue;let source=join(identityDir,name),destination=join(destinationDir,name);if(await pathExists(destination))continue;let read=await readRecord(source);read&&(copies.push({source,destination,bytes:read.bytes}),totalBytes+=read.bytes)}}return copies.length===0?null:{label:"Claude Desktop sessions",itemCount:copies.length,totalBytes,sourceRoots:[subscriptionRoot],destinationRoots:[destinationDir],prompt:[`Copy the ${copies.length} Claude Desktop session record${copies.length===1?"":"s"} (per-session \`.json\` files) under ${codeSpan(subscriptionRoot)} into ${codeSpan(destinationDir)}, keeping each filename.`,"In each copy, rewrite the top-level `model` field to its AI Gateway id by prefixing `anthropic/` when the value has no provider prefix (e.g. `claude-opus-4-8` \u2192 `anthropic/claude-opus-4-8`); keep any suffix such as `[1m]` intact. Leave every other field unchanged.","Use atomic, no-clobber writes with mode 0600; skip records whose destination already exists. Never move, edit, delete, or overwrite an original record."],async apply(){let copied=0,skipped=0,errors=[];for(let copy of copies)try{let read=await readRecord(copy.source);if(!read){skipped+=1;continue}let record={...read.record};typeof record.model=="string"&&(record.model=toGatewayModelId(record.model)),await writeRecordNoClobber(copy.destination,`${JSON.stringify(record)}
28
28
  `)==="copied"?copied+=1:skipped+=1}catch(error){errors.push(`${copy.source}: ${error instanceof Error?error.message:String(error)}`)}return errors.length>0?{copied,skipped,errors}:{copied,skipped}}}}function claudeDir(home){let dir=process.env.CLAUDE_CONFIG_DIR;return dir&&dir.trim()?dir:join2(home,".claude")}var claudeCode={id:"claude-code",displayName:"Claude Code",sessionMigration:{plan:({home})=>planClaudeDesktopSessionMigration(home)},async detect(home){return pathExists(claudeDir(home))},configPath(ctx){return ctx.overrides?.["claude-code"]??join2(claudeDir(ctx.home),"settings.json")},buildPlan(ctx){let path=this.configPath(ctx),env={ANTHROPIC_BASE_URL:resolveGatewayBaseUrl(ctx.baseUrlOverride,GATEWAY_CLAUDE_CODE_BASE_URL),ANTHROPIC_API_KEY:"",CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY:"1",ENABLE_TOOL_SEARCH:"true"},envExports=[];return ctx.useKeychain?envExports.push({name:"ANTHROPIC_AUTH_TOKEN",value:ctx.apiKey}):env.ANTHROPIC_AUTH_TOKEN=ctx.apiKey,{fileChanges:[{path,label:"Claude Code settings",format:"json",...ctx.useKeychain?{}:{mode:384},transform:current=>mergeJson(current,{env})}],envExports,notes:[...ctx.useKeychain?["The Anthropic auth token is read from your shell environment (Keychain-backed).","Open a new terminal so ANTHROPIC_AUTH_TOKEN is loaded, then restart Claude Code."]:["Restart Claude Code to pick up the new settings."],"This command does not configure the Claude Desktop app. To route it through AI Gateway, switch it yourself: in the app menu, choose Help \u2192 Troubleshooting \u2192 Enable Developer Mode\u2026, then Developer \u2192 Configure Third-Party Inference\u2026 See https://vercel.com/docs/ai-gateway/coding-agents/claude-code#with-the-claude-desktop-app","After the Claude Desktop app has launched once on the gateway, re-run this command to copy your existing desktop sessions over."]}}};import{join as join4}from"node:path";import{createHash as createHash2,randomUUID as randomUUID2}from"node:crypto";var regex_default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function validate(uuid){return typeof uuid=="string"&&regex_default.test(uuid)}var validate_default=validate;function parse3(uuid){if(!validate_default(uuid))throw TypeError("Invalid UUID");let v;return Uint8Array.of((v=parseInt(uuid.slice(0,8),16))>>>24,v>>>16&255,v>>>8&255,v&255,(v=parseInt(uuid.slice(9,13),16))>>>8,v&255,(v=parseInt(uuid.slice(14,18),16))>>>8,v&255,(v=parseInt(uuid.slice(19,23),16))>>>8,v&255,(v=parseInt(uuid.slice(24,36),16))/1099511627776&255,v/4294967296&255,v>>>24&255,v>>>16&255,v>>>8&255,v&255)}var parse_default=parse3;var byteToHex=[];for(let i=0;i<256;++i)byteToHex.push((i+256).toString(16).slice(1));function unsafeStringify(arr,offset=0){return(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase()}function stringToBytes(str){str=unescape(encodeURIComponent(str));let bytes=new Uint8Array(str.length);for(let i=0;i<str.length;++i)bytes[i]=str.charCodeAt(i);return bytes}var DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function v35(version,hash,value,namespace,buf,offset){let valueBytes=typeof value=="string"?stringToBytes(value):value,namespaceBytes=typeof namespace=="string"?parse_default(namespace):namespace;if(typeof namespace=="string"&&(namespace=parse_default(namespace)),namespace?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let bytes=new Uint8Array(16+valueBytes.length);if(bytes.set(namespaceBytes),bytes.set(valueBytes,namespaceBytes.length),bytes=hash(bytes),bytes[6]=bytes[6]&15|version,bytes[8]=bytes[8]&63|128,buf){if(offset??=0,offset<0||offset+16>buf.length)throw new RangeError(`UUID byte range ${offset}:${offset+15} is out of buffer bounds`);for(let i=0;i<16;++i)buf[offset+i]=bytes[i];return buf}return unsafeStringify(bytes)}import{createHash}from"node:crypto";function sha1(bytes){return Array.isArray(bytes)?bytes=Buffer.from(bytes):typeof bytes=="string"&&(bytes=Buffer.from(bytes,"utf8")),createHash("sha1").update(bytes).digest()}var sha1_default=sha1;function v5(value,namespace,buf,offset){return v35(80,sha1_default,value,namespace,buf,offset)}v5.DNS=DNS;v5.URL=URL;var v5_default=v5;import{createReadStream,createWriteStream}from"node:fs";import*as fs2 from"node:fs/promises";import{basename,dirname as dirname3,join as join3}from"node:path";import{pipeline}from"node:stream/promises";var ROLLOUT_PATTERN=/^rollout-.*\.jsonl(?:\.zst)?$/,MAX_METADATA_BYTES=1024*1024;function hasCode(error,code){return error.code===code}async function readMeta(path,gateway=!1){let handle=await fs2.open(path,"r"),buffer=new Uint8Array(MAX_METADATA_BYTES+1),length=0,newline=-1;try{for(;length<buffer.length&&newline<0;){let start=length,read=await handle.read(buffer,start,buffer.length-start,start);if(read.bytesRead===0)break;length+=read.bytesRead,newline=buffer.indexOf(10,start)}}finally{await handle.close()}if(newline<0&&length>MAX_METADATA_BYTES)throw new Error(`${basename(path)} metadata exceeds 1 MiB`);let lineEnd=newline<0?length:newline,carriageReturn=buffer[lineEnd-1]===13,record;try{record=JSON.parse(new TextDecoder().decode(buffer.subarray(0,carriageReturn?lineEnd-1:lineEnd)))}catch{return null}let payload=record.payload,id=typeof payload?.id=="string"?payload.id:typeof payload?.session_id=="string"?payload.session_id:"";return record.type!=="session_meta"||!payload||!validate_default(id)||typeof payload.session_id=="string"&&payload.session_id!==id||payload.originator!=="Codex Desktop"&&!(payload.originator==null&&payload.source==="vscode")||(gateway?payload.model_provider!=="vercel":payload.model_provider==="vercel")?null:{record,payload,id,delimiter:newline<0?"":carriageReturn?`\r
29
29
  `:`
30
- `,restOffset:newline<0?length:newline+1}}function codeSpan2(value){return`\`${value.replace(/[`\r\n]/g,"")}\``}async function findRollouts(root){let files=[];async function visit(directory){let entries;try{entries=await fs2.readdir(directory,{withFileTypes:!0})}catch(error){if(hasCode(error,"ENOENT"))return;throw error}for(let entry of entries){let path=join3(directory,entry.name);entry.isDirectory()?await visit(path):entry.isFile()&&ROLLOUT_PATTERN.test(entry.name)&&files.push(path)}}return await visit(root),files}async function planCopy(path,root){let metadata=await readMeta(path),filename=basename(path);if(!metadata||!filename.toLowerCase().includes(metadata.id.toLowerCase()))return null;let destinationId=v5_default(`vercel-ai-gateway/codex/${metadata.id.toLowerCase()}/vercel`,v5_default.URL),destination=join3(dirname3(path),filename.replace(new RegExp(metadata.id,"i"),destinationId)),item={source:path,destination,sourceId:metadata.id,destinationId,bytes:(await fs2.stat(path)).size,root};try{return await fs2.stat(destination),await validateDestination(item),null}catch(error){if(!hasCode(error,"ENOENT"))throw error}return item}async function bodyHash(path,start){let hash=createHash2("sha256");return await pipeline(createReadStream(path,{start}),hash),hash.digest("hex")}async function validateDestination(item){let[source,destination]=await Promise.all([readMeta(item.source),readMeta(item.destination,!0)]),bodies=await Promise.all([bodyHash(item.source,source?.restOffset??0),bodyHash(item.destination,destination?.restOffset??0)]);if(!(source&&destination?.id===item.destinationId&&bodies[0]===bodies[1]))throw new Error(`Existing destination ${basename(item.destination)} is invalid`)}async function copySession(item){let metadata=await readMeta(item.source);if(!metadata)throw new Error("Codex session metadata is no longer valid");if(metadata.id!==item.sourceId)throw new Error("Codex session metadata changed after planning");let updated={...metadata.record,payload:{...metadata.payload,id:item.destinationId,session_id:item.destinationId,model_provider:"vercel"}},temporary=`${item.destination}.tmp-${process.pid}-${randomUUID2()}`;try{return await fs2.writeFile(temporary,`${JSON.stringify(updated)}${metadata.delimiter}`,{flag:"wx",mode:384}),await pipeline(createReadStream(item.source,{start:metadata.restOffset}),createWriteStream(temporary,{flags:"a",mode:384})),await fs2.chmod(temporary,384),await publishNoClobber(temporary,item.destination)?!0:(await validateDestination(item),!1)}finally{await fs2.unlink(temporary).catch(error=>{if(!hasCode(error,"ENOENT"))throw error})}}async function planCodexSessionMigration(home){let codexHome=process.env.CODEX_HOME||join3(home,".codex"),roots=["sessions","archived_sessions"].map(root=>join3(codexHome,root)),files=[];for(let root of roots)files.push(...(await findRollouts(root)).map(path=>({path,root})));if(files.some(file=>file.path.endsWith(".jsonl.zst")))throw new Error("Found compressed Codex sessions; decompress them first, or pass --no-session-migration to leave them unchanged");let copies=[];for(let file of files){let copy=await planCopy(file.path,file.root);copy&&copies.push(copy)}if(copies.length===0)return null;let sourceRoots=[...new Set(copies.map(copy=>copy.root))];return{label:"Codex Desktop sessions",itemCount:copies.length,totalBytes:copies.reduce((total,copy)=>total+copy.bytes,0),sourceRoots,destinationRoots:sourceRoots,prompt:[`Before changing the provider, copy the ${copies.length} top-level Codex Desktop rollout${copies.length===1?"":"s"} with a non-\`vercel\` provider under ${sourceRoots.map(codeSpan2).join(", ")}. Do not copy subagent rollouts whose \`session_id\` differs from \`id\`.`,"For each copy, derive a deterministic UUID v5 using the URL namespace `6ba7b811-9dad-11d1-80b4-00c04fd430c8` and name `vercel-ai-gateway/codex/<source-id>/vercel`. Replace the filename UUID and `session_meta.payload.id`/`session_id`, set `model_provider` to `vercel`, and preserve every later JSONL byte.","Use atomic, no-clobber writes with mode 0600; skip an existing deterministic destination only after validating its metadata and body. Never move, edit, delete, or overwrite an original session file."],async apply(){let copied=0,skipped=0,errors=[];for(let item of copies)try{await copySession(item)?copied++:skipped++}catch(error){errors.push(`${basename(item.source)}: ${error instanceof Error?error.message:String(error)}`)}return{copied,skipped,errors}}}}function codexDir(home){let dir=process.env.CODEX_HOME;return dir&&dir.trim()?dir:join4(home,".codex")}var codex={id:"codex",displayName:"Codex",sessionMigration:{plan:({home})=>planCodexSessionMigration(home)},async detect(home){return pathExists(codexDir(home))},configPath(ctx){return ctx.overrides?.codex??join4(codexDir(ctx.home),"config.toml")},buildPlan(ctx){return{fileChanges:[{path:this.configPath(ctx),label:"Codex config",format:"toml",transform:current=>mergeToml(current,{model_provider:"vercel",model_providers:{vercel:{name:"Vercel AI Gateway",base_url:resolveGatewayBaseUrl(ctx.baseUrlOverride,GATEWAY_CODEX_BASE_URL),env_key:GATEWAY_API_KEY_ENV,wire_api:"responses"}}})}],envExports:[{name:GATEWAY_API_KEY_ENV,value:ctx.apiKey}],notes:["Codex now defaults to the Vercel AI Gateway; pick a model with --model or in config.",`Open a new terminal so ${GATEWAY_API_KEY_ENV} is loaded, or run: export ${GATEWAY_API_KEY_ENV}=<key>`]}}};import{readFile as readFile3,writeFile as writeFile4}from"node:fs/promises";import{access as access2}from"node:fs/promises";import{join as join5}from"node:path";import{homedir}from"node:os";import{spawn}from"node:child_process";var PREFS_FILE="agent-preferences.json",CLAUDE_LEGACY_PLUGIN_ID="vercel-plugin@vercel",CLAUDE_OFFICIAL_MARKETPLACE="claude-plugins-official",CLAUDE_OFFICIAL_MARKETPLACE_SOURCE="anthropics/claude-plugins-official",CLAUDE_OFFICIAL_PLUGIN_ID=`vercel@${CLAUDE_OFFICIAL_MARKETPLACE}`,CLAUDE_DIRECTORY_PLUGIN_ID="vercel@anthropic-plugin-directory",VERCEL_PLUGIN_VERSION_URL="https://raw.githubusercontent.com/vercel/vercel-plugin/main/.claude-plugin/plugin.json",CLAUDE_STATUS_TIMEOUT_MS=15e3,CLAUDE_CHANGE_TIMEOUT_MS=12e4,VERSION_FETCH_TIMEOUT_MS=5e3,promptedAtSchema=external_exports.codec(external_exports.union([external_exports.iso.date(),external_exports.iso.datetime()]),external_exports.date(),{decode:value=>new Date(value),encode:value=>value.toISOString()}),agentPreferencesSchema=external_exports.object({pluginDeclined:external_exports.boolean().optional(),pluginAutoUpdate:external_exports.boolean().optional(),lastPromptedAt:promptedAtSchema.optional(),lastPluginAutoUpdateAttemptedAt:promptedAtSchema.optional(),lastPluginAutoUpdateAttemptedKey:external_exports.string().optional()});async function fileExists(filePath){try{return await access2(filePath),!0}catch{return!1}}async function readPrefs(client){return await client.maybeReadConfig(PREFS_FILE,agentPreferencesSchema)??{}}async function writePrefs(client,prefs){try{await client.writeConfig(PREFS_FILE,agentPreferencesSchema,prefs)}catch{}}async function getSavedPluginAnswer(client){let{pluginDeclined}=await readPrefs(client);return pluginDeclined===void 0?void 0:!pluginDeclined}async function savePluginAnswer(client,accepted){let prefs=await readPrefs(client);prefs.pluginDeclined=!accepted,prefs.pluginAutoUpdate=accepted,await markPromptedToday(client,prefs)}async function hasClaudeVercelPlugin(home){return(await readClaudeInstalledPluginsFromRegistry(join5(claudeDir(home),"plugins","installed_plugins.json"))).some(plugin=>plugin.id===CLAUDE_OFFICIAL_PLUGIN_ID||plugin.id===CLAUDE_DIRECTORY_PLUGIN_ID)}async function readClaudeInstalledPluginsFromRegistry(registryPath=getClaudeInstalledPluginsRegistryPath()){try{let raw=await readFile3(registryPath,"utf-8"),plugins=JSON.parse(raw)?.plugins??{},entries=[];for(let[id,installs]of Object.entries(plugins))if(Array.isArray(installs))for(let install of installs)!install||typeof install!="object"||entries.push({id,...install,enabled:!0});return entries}catch{return[]}}function getClaudeInstalledPluginsRegistryPath(){return join5(homedir(),".claude","plugins","installed_plugins.json")}async function markStaleClaudePluginInstalls(plugins){return Promise.all(plugins.map(async plugin=>plugin.installPath&&!await fileExists(plugin.installPath)?{...plugin,stale:!0}:plugin))}async function removeClaudePluginFromRegistry(pluginId){try{let registryPath=getClaudeInstalledPluginsRegistryPath(),raw=await readFile3(registryPath,"utf-8"),data=JSON.parse(raw);return!data.plugins||!(pluginId in data.plugins)?!1:(delete data.plugins[pluginId],await writeFile4(registryPath,`${JSON.stringify(data,null,2)}
31
- `,"utf-8"),!0)}catch(err){return output_manager_default.debug(`Failed to remove Claude plugin registry entry: ${err}`),!1}}async function markPromptedToday(client,prefs){prefs.lastPromptedAt=new Date,await writePrefs(client,prefs)}async function runCommand(command,args,timeoutMs){return await new Promise(resolve=>{let child=spawn(command,args,{stdio:["ignore","pipe","pipe"]}),stdout="",stderr="",settled=!1,settle=result=>{settled||(settled=!0,clearTimeout(timer),resolve(result))},timer=setTimeout(()=>{child.kill(),child.stdout?.destroy(),child.stderr?.destroy(),child.unref(),settle({exitCode:1,stdout,stderr:`${stderr}Timed out after ${timeoutMs/1e3} seconds.`})},timeoutMs);child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()}),child.on("close",code=>{settle({exitCode:code??1,stdout,stderr})}),child.on("error",err=>{settle({exitCode:1,stdout,stderr:`${stderr}${String(err)}`})})})}async function getClaudeInstalledPlugins(){let result=await runCommand("claude",["plugins","list","--json"],CLAUDE_STATUS_TIMEOUT_MS);if(result.exitCode===0)try{let parsed=JSON.parse(result.stdout);if(Array.isArray(parsed))return markStaleClaudePluginInstalls(parsed)}catch(err){output_manager_default.debug(`Failed to parse Claude plugin list JSON: ${err}`)}else result.stderr.trim().length>0&&output_manager_default.debug(`Failed to run 'claude plugins list --json': ${result.stderr}`);return markStaleClaudePluginInstalls(await readClaudeInstalledPluginsFromRegistry())}async function fetchLatestVercelPluginVersion(){try{let response=await fetch(VERCEL_PLUGIN_VERSION_URL,{signal:AbortSignal.timeout(VERSION_FETCH_TIMEOUT_MS)});if(!response.ok){output_manager_default.debug(`Failed to fetch latest Vercel plugin version: ${response.status}`);return}let manifest=await response.json();return typeof manifest.version=="string"?manifest.version:void 0}catch(err){output_manager_default.debug(`Failed to fetch latest Vercel plugin version: ${err}`);return}}function comparePluginVersions(a,b){if(!a&&!b)return 0;if(!a)return-1;if(!b)return 1;let parse4=value=>value.split(".").map(part=>Number.parseInt(part,10)||0),left=parse4(a),right=parse4(b),maxLength=Math.max(left.length,right.length);for(let i=0;i<maxLength;i++){let l=left[i]??0,r=right[i]??0;if(l>r)return 1;if(l<r)return-1}return 0}function buildClaudePluginStatus(installedPlugins,latestVersion){let legacy=installedPlugins.find(plugin=>plugin.id===CLAUDE_LEGACY_PLUGIN_ID),official=installedPlugins.find(plugin=>plugin.id===CLAUDE_OFFICIAL_PLUGIN_ID),state="none";return legacy&&official?state="both":legacy?state="legacy-only":official&&(state="official-only"),{state,legacy,official,latestVersion}}function buildClaudePluginMigrationPlan(status){let plan={installOfficial:!1,updateOfficial:!1,removeLegacy:!1,removeLegacyMarketplace:!1};switch(status.state){case"none":plan.installOfficial=!0;break;case"legacy-only":plan.installOfficial=!0,plan.removeLegacy=!0,plan.removeLegacyMarketplace=!0;break;case"both":plan.removeLegacy=!0,plan.removeLegacyMarketplace=!0;break;case"official-only":break}return status.official?.version&&status.latestVersion&&comparePluginVersions(status.official.version,status.latestVersion)<0&&(plan.updateOfficial=!0),plan}function hasClaudeMigrationActions(plan){return plan.installOfficial||plan.updateOfficial||plan.removeLegacy||plan.removeLegacyMarketplace}function buildClaudePromptCopy(status,plan){if(plan.installOfficial&&status.state==="none")return{message:"Vercel Plugin for Claude Code is not installed.",confirm:"Would you like to install it now?"};if(plan.installOfficial&&status.state==="legacy-only")return{message:"Update available for Vercel Plugin for Claude Code (legacy -> official).",confirm:"Would you like to update now?"};if(status.state==="both"&&plan.removeLegacy)return{message:"Vercel Plugin for Claude Code has a legacy install to clean up.",confirm:"Would you like to update now?"};if(plan.updateOfficial){let fromVersion=status.official?.version,toVersion=status.latestVersion;return{message:`Update available for Vercel Plugin for Claude Code${fromVersion&&toVersion?` (v${fromVersion} -> v${toVersion})`:""}.`,confirm:"Would you like to update now?"}}return{message:"The Vercel plugin needs attention in Claude Code before your agent harness is fully up to date.",confirm:"Apply the Vercel plugin changes for Claude Code?"}}async function runClaudeCommand(spinnerMessage,successMessage,failureMessage,args,options){output_manager_default.spinner(spinnerMessage);let result=await runCommand("claude",args,CLAUDE_CHANGE_TIMEOUT_MS);return output_manager_default.stopSpinner(),result.exitCode===0?(options?.quietSuccess||output_manager_default.success(successMessage),!0):(output_manager_default.warn(failureMessage),output_manager_default.debug(`Claude command failed: claude ${args.join(" ")}
30
+ `,restOffset:newline<0?length:newline+1}}function codeSpan2(value){return`\`${value.replace(/[`\r\n]/g,"")}\``}async function findRollouts(root){let files=[];async function visit(directory){let entries;try{entries=await fs2.readdir(directory,{withFileTypes:!0})}catch(error){if(hasCode(error,"ENOENT"))return;throw error}for(let entry of entries){let path=join3(directory,entry.name);entry.isDirectory()?await visit(path):entry.isFile()&&ROLLOUT_PATTERN.test(entry.name)&&files.push(path)}}return await visit(root),files}async function planCopy(path,root){let metadata=await readMeta(path),filename=basename(path);if(!metadata||!filename.toLowerCase().includes(metadata.id.toLowerCase()))return null;let destinationId=v5_default(`vercel-ai-gateway/codex/${metadata.id.toLowerCase()}/vercel`,v5_default.URL),destination=join3(dirname3(path),filename.replace(new RegExp(metadata.id,"i"),destinationId)),item={source:path,destination,sourceId:metadata.id,destinationId,bytes:(await fs2.stat(path)).size,root};try{return await fs2.stat(destination),await validateDestination(item),null}catch(error){if(!hasCode(error,"ENOENT"))throw error}return item}async function bodyHash(path,start){let hash=createHash2("sha256");return await pipeline(createReadStream(path,{start}),hash),hash.digest("hex")}async function validateDestination(item){let[source,destination]=await Promise.all([readMeta(item.source),readMeta(item.destination,!0)]),bodies=await Promise.all([bodyHash(item.source,source?.restOffset??0),bodyHash(item.destination,destination?.restOffset??0)]);if(!(source&&destination?.id===item.destinationId&&bodies[0]===bodies[1]))throw new Error(`Existing destination ${basename(item.destination)} is invalid`)}async function copySession(item){let metadata=await readMeta(item.source);if(!metadata)throw new Error("Codex session metadata is no longer valid");if(metadata.id!==item.sourceId)throw new Error("Codex session metadata changed after planning");let updated={...metadata.record,payload:{...metadata.payload,id:item.destinationId,session_id:item.destinationId,model_provider:"vercel"}},temporary=`${item.destination}.tmp-${process.pid}-${randomUUID2()}`;try{return await fs2.writeFile(temporary,`${JSON.stringify(updated)}${metadata.delimiter}`,{flag:"wx",mode:384}),await pipeline(createReadStream(item.source,{start:metadata.restOffset}),createWriteStream(temporary,{flags:"a",mode:384})),await fs2.chmod(temporary,384),await publishNoClobber(temporary,item.destination)?!0:(await validateDestination(item),!1)}finally{await fs2.unlink(temporary).catch(error=>{if(!hasCode(error,"ENOENT"))throw error})}}async function planCodexSessionMigration(home){let codexHome=process.env.CODEX_HOME||join3(home,".codex"),roots=["sessions","archived_sessions"].map(root=>join3(codexHome,root)),files=[];for(let root of roots)files.push(...(await findRollouts(root)).map(path=>({path,root})));if(files.some(file=>file.path.endsWith(".jsonl.zst")))throw new Error("Found compressed Codex sessions; decompress them first, or pass --no-session-migration to leave them unchanged");let copies=[];for(let file of files){let copy=await planCopy(file.path,file.root);copy&&copies.push(copy)}if(copies.length===0)return null;let sourceRoots=[...new Set(copies.map(copy=>copy.root))];return{label:"Codex Desktop sessions",itemCount:copies.length,totalBytes:copies.reduce((total,copy)=>total+copy.bytes,0),sourceRoots,destinationRoots:sourceRoots,prompt:[`Before changing the provider, copy the ${copies.length} top-level Codex Desktop rollout${copies.length===1?"":"s"} with a non-\`vercel\` provider under ${sourceRoots.map(codeSpan2).join(", ")}. Do not copy subagent rollouts whose \`session_id\` differs from \`id\`.`,"For each copy, derive a deterministic UUID v5 using the URL namespace `6ba7b811-9dad-11d1-80b4-00c04fd430c8` and name `vercel-ai-gateway/codex/<source-id>/vercel`. Replace the filename UUID and `session_meta.payload.id`/`session_id`, set `model_provider` to `vercel`, and preserve every later JSONL byte.","Use atomic, no-clobber writes with mode 0600; skip an existing deterministic destination only after validating its metadata and body. Never move, edit, delete, or overwrite an original session file."],async apply(){let copied=0,skipped=0,errors=[];for(let item of copies)try{await copySession(item)?copied++:skipped++}catch(error){errors.push(`${basename(item.source)}: ${error instanceof Error?error.message:String(error)}`)}return{copied,skipped,errors}}}}function codexDir(home){let dir=process.env.CODEX_HOME;return dir&&dir.trim()?dir:join4(home,".codex")}var codex={id:"codex",displayName:"Codex",sessionMigration:{plan:({home})=>planCodexSessionMigration(home)},async detect(home){return pathExists(codexDir(home))},configPath(ctx){return ctx.overrides?.codex??join4(codexDir(ctx.home),"config.toml")},buildPlan(ctx){return{fileChanges:[{path:this.configPath(ctx),label:"Codex config",format:"toml",transform:current=>mergeToml(current,{model_provider:"vercel",model_providers:{vercel:{name:"Vercel AI Gateway",base_url:resolveGatewayBaseUrl(ctx.baseUrlOverride,GATEWAY_CODEX_BASE_URL),env_key:GATEWAY_API_KEY_ENV,wire_api:"responses"}}})}],envExports:[{name:GATEWAY_API_KEY_ENV,value:ctx.apiKey}],notes:["Codex now defaults to the Vercel AI Gateway; pick a model with --model or in config.",`Open a new terminal so ${GATEWAY_API_KEY_ENV} is loaded, or run: export ${GATEWAY_API_KEY_ENV}=<key>`]}}};import{readFile as readFile3,writeFile as writeFile4}from"node:fs/promises";import{access as access2}from"node:fs/promises";import{join as join6}from"node:path";import{homedir as homedir2}from"node:os";import{spawn}from"node:child_process";var import_which=__toESM(require_lib(),1);import{existsSync}from"node:fs";import{homedir}from"node:os";import{dirname as dirname4,isAbsolute,join as join5,relative,resolve,sep}from"node:path";var WINDOWS_SHIM=/\.(cmd|bat)$/i,DEFAULT_PATHEXT=".COM;.EXE;.BAT;.CMD";function hasLocalNode(projectRoot){return(process.env.PATHEXT||DEFAULT_PATHEXT).split(";").filter(Boolean).some(extension=>existsSync(join5(projectRoot,`node${extension}`)))}function pathInside(directory,target){let path=relative(directory,target);return isAbsolute(path)||path===".."||path.startsWith(`..${sep}`)?null:path}function inGitWorkTree(directory){let current=directory;for(;;){if(existsSync(join5(current,".git")))return!0;let parent=dirname4(current);if(parent===current)return!1;current=parent}}function containsHomeDirectory(directory){try{let home=homedir();return isAbsolute(home)&&pathInside(directory,home)!==null}catch{return!1}}function isInstalledProgram(directory,segments){return segments.some(segment=>segment.toLowerCase()==="node_modules")||!directory.endsWith(sep)&&!containsHomeDirectory(directory)?!1:!inGitWorkTree(directory)}function resolveAgentExecutable(command,cwd=process.cwd()){let executable=import_which.default.sync(command,{nothrow:!0});if(!executable||!isAbsolute(executable))return null;let projectRoot=resolve(cwd),resolved=resolve(executable),pathInProject=pathInside(projectRoot,resolved);if(pathInProject!==null){let segments=pathInProject.split(sep);if(segments.length<2||!isInstalledProgram(projectRoot,segments))return null}return process.platform==="win32"&&WINDOWS_SHIM.test(resolved)&&!existsSync(join5(dirname4(resolved),"node.exe"))&&hasLocalNode(projectRoot)?null:resolved}var PREFS_FILE="agent-preferences.json",CLAUDE_LEGACY_PLUGIN_ID="vercel-plugin@vercel",CLAUDE_OFFICIAL_MARKETPLACE="claude-plugins-official",CLAUDE_OFFICIAL_MARKETPLACE_SOURCE="anthropics/claude-plugins-official",CLAUDE_OFFICIAL_PLUGIN_ID=`vercel@${CLAUDE_OFFICIAL_MARKETPLACE}`,CLAUDE_DIRECTORY_PLUGIN_ID="vercel@anthropic-plugin-directory",VERCEL_PLUGIN_VERSION_URL="https://raw.githubusercontent.com/vercel/vercel-plugin/main/.claude-plugin/plugin.json",CLAUDE_STATUS_TIMEOUT_MS=15e3,CLAUDE_CHANGE_TIMEOUT_MS=12e4,VERSION_FETCH_TIMEOUT_MS=5e3,promptedAtSchema=external_exports.codec(external_exports.union([external_exports.iso.date(),external_exports.iso.datetime()]),external_exports.date(),{decode:value=>new Date(value),encode:value=>value.toISOString()}),agentPreferencesSchema=external_exports.object({pluginDeclined:external_exports.boolean().optional(),pluginAutoUpdate:external_exports.boolean().optional(),lastPromptedAt:promptedAtSchema.optional(),lastPluginAutoUpdateAttemptedAt:promptedAtSchema.optional(),lastPluginAutoUpdateAttemptedKey:external_exports.string().optional()});async function fileExists(filePath){try{return await access2(filePath),!0}catch{return!1}}async function readPrefs(client){return await client.maybeReadConfig(PREFS_FILE,agentPreferencesSchema)??{}}async function writePrefs(client,prefs){try{await client.writeConfig(PREFS_FILE,agentPreferencesSchema,prefs)}catch{}}async function getSavedPluginAnswer(client){let{pluginDeclined}=await readPrefs(client);return pluginDeclined===void 0?void 0:!pluginDeclined}async function savePluginAnswer(client,accepted){let prefs=await readPrefs(client);prefs.pluginDeclined=!accepted,prefs.pluginAutoUpdate=accepted,await markPromptedToday(client,prefs)}async function hasClaudeVercelPlugin(home){return(await readClaudeInstalledPluginsFromRegistry(join6(claudeDir(home),"plugins","installed_plugins.json"))).some(plugin=>plugin.id===CLAUDE_OFFICIAL_PLUGIN_ID||plugin.id===CLAUDE_DIRECTORY_PLUGIN_ID)}async function readClaudeInstalledPluginsFromRegistry(registryPath=getClaudeInstalledPluginsRegistryPath()){try{let raw=await readFile3(registryPath,"utf-8"),plugins=JSON.parse(raw)?.plugins??{},entries=[];for(let[id,installs]of Object.entries(plugins))if(Array.isArray(installs))for(let install of installs)!install||typeof install!="object"||entries.push({id,...install,enabled:!0});return entries}catch{return[]}}function getClaudeInstalledPluginsRegistryPath(){return join6(homedir2(),".claude","plugins","installed_plugins.json")}async function markStaleClaudePluginInstalls(plugins){return Promise.all(plugins.map(async plugin=>plugin.installPath&&!await fileExists(plugin.installPath)?{...plugin,stale:!0}:plugin))}async function removeClaudePluginFromRegistry(pluginId){try{let registryPath=getClaudeInstalledPluginsRegistryPath(),raw=await readFile3(registryPath,"utf-8"),data=JSON.parse(raw);return!data.plugins||!(pluginId in data.plugins)?!1:(delete data.plugins[pluginId],await writeFile4(registryPath,`${JSON.stringify(data,null,2)}
31
+ `,"utf-8"),!0)}catch(err){return output_manager_default.debug(`Failed to remove Claude plugin registry entry: ${err}`),!1}}async function markPromptedToday(client,prefs){prefs.lastPromptedAt=new Date,await writePrefs(client,prefs)}async function runCommand(command,args,timeoutMs){let executable=resolveAgentExecutable(command);return executable?await new Promise(resolve2=>{let child;try{child=spawn(executable,args,{stdio:["ignore","pipe","pipe"]})}catch(err){resolve2({exitCode:1,stdout:"",stderr:String(err)});return}let stdout="",stderr="",settled=!1,settle=result=>{settled||(settled=!0,clearTimeout(timer),resolve2(result))},timer=setTimeout(()=>{child.kill(),child.stdout?.destroy(),child.stderr?.destroy(),child.unref(),settle({exitCode:1,stdout,stderr:`${stderr}Timed out after ${timeoutMs/1e3} seconds.`})},timeoutMs);child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()}),child.on("close",code=>{settle({exitCode:code??1,stdout,stderr})}),child.on("error",err=>{settle({exitCode:1,stdout,stderr:`${stderr}${String(err)}`})})}):{exitCode:1,stdout:"",stderr:`${command} was not found outside the project directory.`}}async function getClaudeInstalledPlugins(){let result=await runCommand("claude",["plugins","list","--json"],CLAUDE_STATUS_TIMEOUT_MS);if(result.exitCode===0)try{let parsed=JSON.parse(result.stdout);if(Array.isArray(parsed))return markStaleClaudePluginInstalls(parsed)}catch(err){output_manager_default.debug(`Failed to parse Claude plugin list JSON: ${err}`)}else result.stderr.trim().length>0&&output_manager_default.debug(`Failed to run 'claude plugins list --json': ${result.stderr}`);return markStaleClaudePluginInstalls(await readClaudeInstalledPluginsFromRegistry())}async function fetchLatestVercelPluginVersion(){try{let response=await fetch(VERCEL_PLUGIN_VERSION_URL,{signal:AbortSignal.timeout(VERSION_FETCH_TIMEOUT_MS)});if(!response.ok){output_manager_default.debug(`Failed to fetch latest Vercel plugin version: ${response.status}`);return}let manifest=await response.json();return typeof manifest.version=="string"?manifest.version:void 0}catch(err){output_manager_default.debug(`Failed to fetch latest Vercel plugin version: ${err}`);return}}function comparePluginVersions(a,b){if(!a&&!b)return 0;if(!a)return-1;if(!b)return 1;let parse4=value=>value.split(".").map(part=>Number.parseInt(part,10)||0),left=parse4(a),right=parse4(b),maxLength=Math.max(left.length,right.length);for(let i=0;i<maxLength;i++){let l=left[i]??0,r=right[i]??0;if(l>r)return 1;if(l<r)return-1}return 0}function buildClaudePluginStatus(installedPlugins,latestVersion){let legacy=installedPlugins.find(plugin=>plugin.id===CLAUDE_LEGACY_PLUGIN_ID),official=installedPlugins.find(plugin=>plugin.id===CLAUDE_OFFICIAL_PLUGIN_ID),state="none";return legacy&&official?state="both":legacy?state="legacy-only":official&&(state="official-only"),{state,legacy,official,latestVersion}}function buildClaudePluginMigrationPlan(status){let plan={installOfficial:!1,updateOfficial:!1,removeLegacy:!1,removeLegacyMarketplace:!1};switch(status.state){case"none":plan.installOfficial=!0;break;case"legacy-only":plan.installOfficial=!0,plan.removeLegacy=!0,plan.removeLegacyMarketplace=!0;break;case"both":plan.removeLegacy=!0,plan.removeLegacyMarketplace=!0;break;case"official-only":break}return status.official?.version&&status.latestVersion&&comparePluginVersions(status.official.version,status.latestVersion)<0&&(plan.updateOfficial=!0),plan}function hasClaudeMigrationActions(plan){return plan.installOfficial||plan.updateOfficial||plan.removeLegacy||plan.removeLegacyMarketplace}function buildClaudePromptCopy(status,plan){if(plan.installOfficial&&status.state==="none")return{message:"Vercel Plugin for Claude Code is not installed.",confirm:"Would you like to install it now?"};if(plan.installOfficial&&status.state==="legacy-only")return{message:"Update available for Vercel Plugin for Claude Code (legacy -> official).",confirm:"Would you like to update now?"};if(status.state==="both"&&plan.removeLegacy)return{message:"Vercel Plugin for Claude Code has a legacy install to clean up.",confirm:"Would you like to update now?"};if(plan.updateOfficial){let fromVersion=status.official?.version,toVersion=status.latestVersion;return{message:`Update available for Vercel Plugin for Claude Code${fromVersion&&toVersion?` (v${fromVersion} -> v${toVersion})`:""}.`,confirm:"Would you like to update now?"}}return{message:"The Vercel plugin needs attention in Claude Code before your agent harness is fully up to date.",confirm:"Apply the Vercel plugin changes for Claude Code?"}}async function runClaudeCommand(spinnerMessage,successMessage,failureMessage,args,options){output_manager_default.spinner(spinnerMessage);let result=await runCommand("claude",args,CLAUDE_CHANGE_TIMEOUT_MS);return output_manager_default.stopSpinner(),result.exitCode===0?(options?.quietSuccess||output_manager_default.success(successMessage),!0):(output_manager_default.warn(failureMessage),output_manager_default.debug(`Claude command failed: claude ${args.join(" ")}
32
32
  ${result.stderr||result.stdout}`),!1)}async function ensureClaudeOfficialMarketplace(){output_manager_default.spinner("Checking Claude plugin marketplaces\u2026");let result=await runCommand("claude",["plugins","marketplace","list","--json"],CLAUDE_STATUS_TIMEOUT_MS);output_manager_default.stopSpinner();let marketplaces;try{marketplaces=JSON.parse(result.stdout)}catch{}if(result.exitCode!==0||!Array.isArray(marketplaces))return output_manager_default.debug(`Failed to list Claude plugin marketplaces: ${result.stderr||result.stdout}`),!0;if(marketplaces.some(marketplace=>marketplace?.name===CLAUDE_OFFICIAL_MARKETPLACE))return!0;let added=await runClaudeCommand("Adding the official Claude plugin marketplace...","Added the official Claude plugin marketplace","Failed to add the official Claude plugin marketplace.",["plugins","marketplace","add",CLAUDE_OFFICIAL_MARKETPLACE_SOURCE],{quietSuccess:!0});return added||output_manager_default.log(`Setup command: claude plugins marketplace add ${CLAUDE_OFFICIAL_MARKETPLACE_SOURCE}`),added}async function removeStaleLegacyClaudePlugin(removeMarketplace){output_manager_default.spinner("Removing the stale legacy Vercel Claude plugin...");let removedRegistryEntry=await removeClaudePluginFromRegistry(CLAUDE_LEGACY_PLUGIN_ID);if(output_manager_default.stopSpinner(),!removedRegistryEntry)return output_manager_default.warn("Could not remove the stale legacy Vercel Claude plugin registry entry."),{removedPlugin:!1,complete:!1};if(output_manager_default.success("Removed the stale legacy Vercel Claude plugin"),removeMarketplace){let removedMarketplace=await runClaudeCommand("Removing the legacy Vercel marketplace...","Removed the legacy Vercel marketplace","Removed the stale legacy Vercel plugin, but could not remove the legacy marketplace.",["plugins","marketplace","remove","vercel"],{quietSuccess:!0});return removedMarketplace||output_manager_default.log("Cleanup command: claude plugins marketplace remove vercel"),{removedPlugin:!0,complete:removedMarketplace}}return{removedPlugin:!0,complete:!0}}async function runClaudeMigration(plan){let removedStaleLegacy=!1,complete=!0;if(plan.removeLegacy&&(await getClaudePluginStatus()).legacy?.stale){let cleanup=await removeStaleLegacyClaudePlugin(plan.removeLegacyMarketplace);removedStaleLegacy=cleanup.removedPlugin,complete=cleanup.complete}if(plan.installOfficial){if(!await ensureClaudeOfficialMarketplace()||!await runClaudeCommand("Installing the official Vercel Claude plugin...","Updated the Vercel plugin","Failed to install the official Vercel Claude plugin.",["plugins","install",CLAUDE_OFFICIAL_PLUGIN_ID]))return!1}else if(plan.updateOfficial&&!await runClaudeCommand("Updating the official Vercel Claude plugin...","Updated the Vercel plugin","Failed to update the official Vercel Claude plugin.",["plugins","update",CLAUDE_OFFICIAL_PLUGIN_ID]))return!1;let statusAfterInstall=await getClaudePluginStatus();return statusAfterInstall.official?plan.removeLegacy&&statusAfterInstall.legacy&&!await runClaudeCommand("Removing the legacy Vercel Claude plugin...","Removed the legacy Vercel Claude plugin","Installed the official Vercel Claude plugin, but could not remove the legacy install.",["plugins","uninstall",CLAUDE_LEGACY_PLUGIN_ID],{quietSuccess:!0})?(output_manager_default.log(`Cleanup command: claude plugins uninstall ${CLAUDE_LEGACY_PLUGIN_ID}`),!1):plan.removeLegacyMarketplace&&!removedStaleLegacy&&!(await getClaudePluginStatus()).legacy&&!await runClaudeCommand("Removing the legacy Vercel marketplace...","Removed the legacy Vercel marketplace","Removed the legacy Vercel plugin, but could not remove the legacy marketplace.",["plugins","marketplace","remove","vercel"],{quietSuccess:!0})?(output_manager_default.log("Cleanup command: claude plugins marketplace remove vercel"),!1):complete:(output_manager_default.warn("Skipping Claude cleanup because the official Vercel plugin is not installed."),!1)}async function getClaudePluginStatus(){output_manager_default.spinner("Checking the Vercel plugin for Claude Code\u2026");try{let[installedPlugins,latestVersion]=await Promise.all([getClaudeInstalledPlugins(),fetchLatestVercelPluginVersion()]);return buildClaudePluginStatus(installedPlugins,latestVersion)}finally{output_manager_default.stopSpinner()}}function describeClaudePlan(plan){let actions=[];return plan.installOfficial&&actions.push("install the official plugin"),plan.updateOfficial&&actions.push("update the official plugin"),plan.removeLegacy&&actions.push("remove the legacy plugin"),plan.removeLegacyMarketplace&&actions.push("remove the legacy marketplace"),actions.join(", ")}async function setupVercelPlugin(client,opts){if(!await claudeCode.detect(opts.home))return{status:"not_detected",message:"Claude Code was not detected on this machine."};let status=await getClaudePluginStatus();if(status.official?.stale)return{status:"failed",message:"The installed Vercel plugin files are missing. Run `claude plugins uninstall vercel@claude-plugins-official`, then run `vercel setup plugin --agent claude-code` to reinstall it."};let plan=buildClaudePluginMigrationPlan(status);if(!hasClaudeMigrationActions(plan))return{status:"up_to_date",message:`Vercel plugin for Claude Code is installed${status.official?.version?` (v${status.official.version})`:""}.`};let copy=buildClaudePromptCopy(status,plan);if(opts.dryRun)return{status:"dry_run",message:`${copy.message} Setup would ${describeClaudePlan(plan)}.`,action:plan.installOfficial?"install":"update"};let prefs=await readPrefs(client);if(!opts.yes){if(!opts.canPrompt)return{status:"confirmation_required",message:`${copy.message} Re-run with --yes to apply it.`};output_manager_default.print(` ${copy.message}
33
- `);let accepted=await client.input.confirm(copy.confirm,!0);if(await markPromptedToday(client,prefs),!accepted)return prefs.pluginDeclined=!0,prefs.pluginAutoUpdate=!1,await writePrefs(client,prefs),{status:"declined",message:"Skipped the Vercel plugin for Claude Code."}}prefs.pluginDeclined=!1,prefs.pluginAutoUpdate=!0,await writePrefs(client,prefs);let migrated=await runClaudeMigration(plan),after=await getClaudePluginStatus();if(!after.official)return{status:"failed",message:"Failed to install the Vercel plugin for Claude Code. Run `claude plugins install vercel@claude-plugins-official` to install it manually."};let remaining=buildClaudePluginMigrationPlan({...after,latestVersion:plan.updateOfficial?status.latestVersion:void 0});if(!migrated||after.official.stale||hasClaudeMigrationActions(remaining))return{status:"failed",message:"Failed to complete Vercel plugin setup for Claude Code. Re-run `vercel setup plugin --agent claude-code --yes` to retry."};let version=after.official.version?` v${after.official.version}`:"";return{status:plan.installOfficial?"installed":"updated",message:`${plan.installOfficial?"Installed":"Updated"} the Vercel plugin for Claude Code${version}.`}}var import_execa=__toESM(require_execa(),1);init_dist();import{readFile as readFile4}from"node:fs/promises";import{join as join6}from"node:path";var MARKETPLACE="openai-curated-remote",PLUGIN_ID=`vercel@${MARKETPLACE}`,INSTALL_COMMAND=`codex plugin add ${PLUGIN_ID}`,SIGN_IN_MESSAGE="Can't install the Vercel plugin for Codex without a ChatGPT sign-in. Run `codex login`, then `vercel setup plugin --agent codex`.",pluginListSchema=external_exports.object({installed:external_exports.array(external_exports.object({pluginId:external_exports.string(),enabled:external_exports.boolean(),version:external_exports.string().nullable().optional()}))});async function runCodex(args){let{stdout}=await(0,import_execa.default)("codex",args,{encoding:"utf8",stdin:"ignore",timeout:6e4,maxBuffer:1048576});return stdout}function needsChatGptSignIn(err){let{message,stderr}=err;return[message,stderr].some(text=>typeof text=="string"&&/chatgpt authentication required/i.test(text))}async function installedPlugin(){let stdout=await runCodex(["plugin","list","--marketplace",MARKETPLACE,"--json"]),{installed}=pluginListSchema.parse(JSON.parse(stdout));return installed.find(plugin=>plugin.pluginId===PLUGIN_ID)}async function hasCodexVercelPlugin(home){try{let raw=await readFile4(join6(codexDir(home),"config.toml"),"utf8"),entry=parse2(raw).plugins?.[PLUGIN_ID];return typeof entry=="object"&&entry.enabled!==!1}catch{return!1}}async function setupCodexPlugin(client,opts){if(!await codex.detect(opts.home))return{status:"not_detected",message:"Codex was not detected on this machine."};let before;output_manager_default.spinner("Checking the Vercel plugin for Codex\u2026");try{before=await installedPlugin()}catch(err){return{status:"failed",message:needsChatGptSignIn(err)?SIGN_IN_MESSAGE:"Couldn't inspect Codex plugins. Install or update the Codex CLI, sign in with `codex login`, then re-run `vercel setup plugin --agent codex`."}}finally{output_manager_default.stopSpinner()}if(before?.enabled)return{status:"up_to_date",message:`Vercel plugin for Codex is installed${before.version?` (v${before.version})`:""}.`};let action=before?"enable":"install";if(opts.dryRun)return{status:"dry_run",action,message:`Setup would ${action} the Vercel plugin for Codex from the OpenAI marketplace.`};if(!opts.yes){if(!opts.canPrompt)return{status:"confirmation_required",message:`Re-run with --yes to ${action} the Vercel plugin for Codex.`};if(printAlignedLabel("Plugin","Vercel for Codex (OpenAI marketplace)"),!await client.input.confirm(before?"Enable this plugin?":"Install this plugin?",!0))return{status:"declined",message:"Skipped the Vercel plugin for Codex."}}output_manager_default.spinner(`${before?"Enabling":"Installing"} the Vercel plugin for Codex\u2026`);try{let stdout=await runCodex(["plugin","add",PLUGIN_ID,"--json"]),install=external_exports.object({appsNeedingAuth:external_exports.array(external_exports.unknown()).optional()}).parse(JSON.parse(stdout)),after=await installedPlugin();if(!after?.enabled)return{status:"failed",message:"The Vercel plugin is not enabled in Codex. Open Codex's /plugins browser, enable Vercel, then re-run `vercel setup plugin --agent codex`."};let version=after.version?` v${after.version}`:"",connection=install.appsNeedingAuth?.length?" Connect Vercel in Codex's /plugins browser to use its connected tools.":" Start a new Codex session to load the plugin.";return{status:before?"enabled":"installed",message:`${before?"Enabled":"Installed"} the Vercel plugin for Codex${version}.${connection}`}}catch(err){return{status:"failed",message:needsChatGptSignIn(err)?SIGN_IN_MESSAGE:`Failed to set up the Vercel plugin for Codex. Run \`${INSTALL_COMMAND}\` to finish setup in Codex.`}}finally{output_manager_default.stopSpinner()}}export{pathExists,isFile,isSymlink,readFileOrNull,parseJsonObjectOrNull,mergeJson,mergeJsonc,mergeToml,MANAGED_BLOCK_START,MANAGED_BLOCK_END,upsertManagedBlock,ensureMode,backupFile,writeConfigFile,GATEWAY_ANTHROPIC_BASE_URL,GATEWAY_CODING_AGENT_BASE_URL,GATEWAY_CURSOR_BASE_URL,GATEWAY_API_KEY_ENV,GATEWAY_DEFAULT_MODEL,KEY_PLACEHOLDER,resolveGatewayBaseUrl,maskSecret,claudeCode,codex,getSavedPluginAnswer,savePluginAnswer,hasClaudeVercelPlugin,setupVercelPlugin,hasCodexVercelPlugin,setupCodexPlugin};
33
+ `);let accepted=await client.input.confirm(copy.confirm,!0);if(await markPromptedToday(client,prefs),!accepted)return prefs.pluginDeclined=!0,prefs.pluginAutoUpdate=!1,await writePrefs(client,prefs),{status:"declined",message:"Skipped the Vercel plugin for Claude Code."}}prefs.pluginDeclined=!1,prefs.pluginAutoUpdate=!0,await writePrefs(client,prefs);let migrated=await runClaudeMigration(plan),after=await getClaudePluginStatus();if(!after.official)return{status:"failed",message:"Failed to install the Vercel plugin for Claude Code. Run `claude plugins install vercel@claude-plugins-official` to install it manually."};let remaining=buildClaudePluginMigrationPlan({...after,latestVersion:plan.updateOfficial?status.latestVersion:void 0});if(!migrated||after.official.stale||hasClaudeMigrationActions(remaining))return{status:"failed",message:"Failed to complete Vercel plugin setup for Claude Code. Re-run `vercel setup plugin --agent claude-code --yes` to retry."};let version=after.official.version?` v${after.official.version}`:"";return{status:plan.installOfficial?"installed":"updated",message:`${plan.installOfficial?"Installed":"Updated"} the Vercel plugin for Claude Code${version}.`}}var import_execa=__toESM(require_execa(),1);init_dist();import{readFile as readFile4}from"node:fs/promises";import{join as join7}from"node:path";var MARKETPLACE="openai-curated-remote",PLUGIN_ID=`vercel@${MARKETPLACE}`,INSTALL_COMMAND=`codex plugin add ${PLUGIN_ID}`,SIGN_IN_MESSAGE="Can't install the Vercel plugin for Codex without a ChatGPT sign-in. Run `codex login`, then `vercel setup plugin --agent codex`.",pluginListSchema=external_exports.object({installed:external_exports.array(external_exports.object({pluginId:external_exports.string(),enabled:external_exports.boolean(),version:external_exports.string().nullable().optional()}))});async function runCodex(args){let executable=resolveAgentExecutable("codex");if(!executable)throw new Error("codex was not found outside the project directory.");let{stdout}=await(0,import_execa.default)(executable,args,{encoding:"utf8",stdin:"ignore",timeout:6e4,maxBuffer:1024*1024});return stdout}function needsChatGptSignIn(err){let{message,stderr}=err;return[message,stderr].some(text=>typeof text=="string"&&/chatgpt authentication required/i.test(text))}async function installedPlugin(){let stdout=await runCodex(["plugin","list","--marketplace",MARKETPLACE,"--json"]),{installed}=pluginListSchema.parse(JSON.parse(stdout));return installed.find(plugin=>plugin.pluginId===PLUGIN_ID)}async function hasCodexVercelPlugin(home){try{let raw=await readFile4(join7(codexDir(home),"config.toml"),"utf8"),entry=parse2(raw).plugins?.[PLUGIN_ID];return typeof entry=="object"&&entry.enabled!==!1}catch{return!1}}async function setupCodexPlugin(client,opts){if(!await codex.detect(opts.home))return{status:"not_detected",message:"Codex was not detected on this machine."};let before;output_manager_default.spinner("Checking the Vercel plugin for Codex\u2026");try{before=await installedPlugin()}catch(err){return{status:"failed",message:needsChatGptSignIn(err)?SIGN_IN_MESSAGE:"Couldn't inspect Codex plugins. Install or update the Codex CLI, sign in with `codex login`, then re-run `vercel setup plugin --agent codex`."}}finally{output_manager_default.stopSpinner()}if(before?.enabled)return{status:"up_to_date",message:`Vercel plugin for Codex is installed${before.version?` (v${before.version})`:""}.`};let action=before?"enable":"install";if(opts.dryRun)return{status:"dry_run",action,message:`Setup would ${action} the Vercel plugin for Codex from the OpenAI marketplace.`};if(!opts.yes){if(!opts.canPrompt)return{status:"confirmation_required",message:`Re-run with --yes to ${action} the Vercel plugin for Codex.`};if(printAlignedLabel("Plugin","Vercel for Codex (OpenAI marketplace)"),!await client.input.confirm(before?"Enable this plugin?":"Install this plugin?",!0))return{status:"declined",message:"Skipped the Vercel plugin for Codex."}}output_manager_default.spinner(`${before?"Enabling":"Installing"} the Vercel plugin for Codex\u2026`);try{let stdout=await runCodex(["plugin","add",PLUGIN_ID,"--json"]),install=external_exports.object({appsNeedingAuth:external_exports.array(external_exports.unknown()).optional()}).parse(JSON.parse(stdout)),after=await installedPlugin();if(!after?.enabled)return{status:"failed",message:"The Vercel plugin is not enabled in Codex. Open Codex's /plugins browser, enable Vercel, then re-run `vercel setup plugin --agent codex`."};let version=after.version?` v${after.version}`:"",connection=install.appsNeedingAuth?.length?" Connect Vercel in Codex's /plugins browser to use its connected tools.":" Start a new Codex session to load the plugin.";return{status:before?"enabled":"installed",message:`${before?"Enabled":"Installed"} the Vercel plugin for Codex${version}.${connection}`}}catch(err){return{status:"failed",message:needsChatGptSignIn(err)?SIGN_IN_MESSAGE:`Failed to set up the Vercel plugin for Codex. Run \`${INSTALL_COMMAND}\` to finish setup in Codex.`}}finally{output_manager_default.stopSpinner()}}export{pathExists,isFile,isSymlink,readFileOrNull,parseJsonObjectOrNull,mergeJson,mergeJsonc,mergeToml,MANAGED_BLOCK_START,MANAGED_BLOCK_END,upsertManagedBlock,ensureMode,backupFile,writeConfigFile,GATEWAY_ANTHROPIC_BASE_URL,GATEWAY_CODING_AGENT_BASE_URL,GATEWAY_CURSOR_BASE_URL,GATEWAY_API_KEY_ENV,GATEWAY_DEFAULT_MODEL,KEY_PLACEHOLDER,resolveGatewayBaseUrl,maskSecret,claudeCode,codex,resolveAgentExecutable,getSavedPluginAnswer,savePluginAnswer,hasClaudeVercelPlugin,setupVercelPlugin,hasCodexVercelPlugin,setupCodexPlugin};
@@ -4,7 +4,7 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{commands,commandsStructs}from"./chunk-XR2J7PQN.js";import{DEPRECATED_BUDGET_ACTIONS,budgetCommand}from"./chunk-C35SG42R.js";import{printError}from"./chunk-33HVDSWP.js";import{BETA_COMMANDS,createHelpTheme,help,helpCommand,resolveHelpTarget}from"./chunk-5KSBRQI2.js";import{TelemetryClient,readLaunch,require_ci_info}from"./chunk-KDCODXVL.js";import{parseArguments,takeCommand}from"./chunk-CINNNQDJ.js";import{AGENT_STATUS,shouldEmitNonInteractiveCommandError,writeAgentError}from"./chunk-4SS6W6JK.js";import{getCommandNamePlain}from"./chunk-B4KA3ZH2.js";import{output_manager_default}from"./chunk-AP6DZGTK.js";import{getFlagsSpecification,globalCliFlagTakesValue}from"./chunk-CFJBDBYH.js";import{__toESM}from"./chunk-BZENIQ7N.js";var budgets={to:["billing","budgets"],actions:{of:budgetCommand,renamed:DEPRECATED_BUDGET_ACTIONS}},MOVED_COMMANDS={usage:{to:["billing","usage"]},budgets,budget:budgets};function getMovedCommand(name){return Object.hasOwn(MOVED_COMMANDS,name)?MOVED_COMMANDS[name].to:void 0}function allOptions(command){return[...command.options,...(command.subcommands??[]).flatMap(allOptions)]}function rewriteMovedCommand(argv){let tokens=argv.slice(2),root;try{root=takeCommand(tokens,{})}catch{return}let move=root.command&&Object.hasOwn(MOVED_COMMANDS,root.command)?MOVED_COMMANDS[root.command]:void 0;if(!(!root.command||!move)){if(move.actions){let{of,renamed}=move.actions;try{let action=takeCommand(tokens.slice(root.index+1),getFlagsSpecification(allOptions(of))),actionTo=action.command&&Object.hasOwn(renamed,action.command)?renamed[action.command]:void 0;if(actionTo){let to=[...move.to,actionTo];return argv.splice(2,tokens.length,...tokens.slice(0,root.index),...to,...action.args),{from:`${root.command} ${action.command}`,to:to.join(" ")}}}catch{}}return argv.splice(2+root.index,1,...move.to),{from:root.command,to:move.to.join(" ")}}}var import_ci_info=__toESM(require_ci_info(),1);var RootTelemetryClient=class extends TelemetryClient{trackCliExtension(){this.trackExtension()}trackCliDefaultDeploy(defaultDeploy){defaultDeploy&&this.trackDefaultDeploy()}trackCliCommandAgent(actual){this.trackCliCommand({command:"agent",value:actual})}trackCliCommandAgentRuns(actual){this.trackCliCommand({command:"agent-runs",value:actual})}trackCliCommandAiGateway(actual){this.trackCliCommand({command:"ai-gateway",value:actual})}trackCliCommandTokenPass(actual){this.trackCliCommand({command:"token-pass",value:actual})}trackCliCommandAlias(actual){this.trackCliCommand({command:"alias",value:actual})}trackCliCommandActivity(actual){this.trackCliCommand({command:"activity",value:actual})}trackCliCommandAlerts(actual){this.trackCliCommand({command:"alerts",value:actual})}trackCliCommandApi(actual){this.trackCliCommand({command:"api",value:actual})}trackCliCommandBilling(actual){this.trackCliCommand({command:"billing",value:actual})}trackCliCommandBisect(actual){this.trackCliCommand({command:"bisect",value:actual})}trackCliCommandBlob(actual){this.trackCliCommand({command:"blob",value:actual})}trackCliCommandBoard(actual){this.trackCliCommand({command:"board",value:actual})}trackCliCommandBudgets(actual){this.trackCliCommand({command:"budgets",value:actual})}trackCliCommandBuild(actual){this.trackCliCommand({command:"build",value:actual})}trackCliCommandBuy(actual){this.trackCliCommand({command:"buy",value:actual})}trackCliCommandCache(actual){this.trackCliCommand({command:"cache",value:actual})}trackCliCommandCerts(actual){this.trackCliCommand({command:"certs",value:actual})}trackCliCommandCi(actual){this.trackCliCommand({command:"ci",value:actual})}trackCliCommandChangelog(actual){this.trackCliCommand({command:"changelog",value:actual})}trackCliCommandComments(actual){this.trackCliCommand({command:"comments",value:actual})}trackCliCommandConnex(actual){this.trackCliCommand({command:"connect",value:actual})}trackCliCommandCrons(actual){this.trackCliCommand({command:"crons",value:actual})}trackCliCommandCurl(actual){this.trackCliCommand({command:"curl",value:actual})}trackCliCommandDaemons(actual){this.trackCliCommand({command:"daemons",value:actual})}trackCliCommandDrives(actual){this.trackCliCommand({command:"drives",value:actual})}trackCliCommandDeploy(actual){this.trackCliCommand({command:"deploy",value:actual})}trackCliCommandOidcPolicies(actual){this.trackCliCommand({command:"oidc-policies",value:actual})}trackCliCommandDeployHooks(actual){this.trackCliCommand({command:"deploy-hooks",value:actual})}trackCliCommandDev(actual){this.trackCliCommand({command:"dev",value:actual})}trackCliCommandDoctor(actual){this.trackCliCommand({command:"doctor",value:actual})}trackCliCommandDomains(actual){this.trackCliCommand({command:"domains",value:actual})}trackCliCommandDrains(actual){this.trackCliCommand({command:"drains",value:actual})}trackCliCommandDns(actual){this.trackCliCommand({command:"dns",value:actual})}trackCliCommandEnv(actual){this.trackCliCommand({command:"env",value:actual})}trackCliCommandExperiments(actual){this.trackCliCommand({command:"experiments",value:actual})}trackCliCommandFirewall(actual){this.trackCliCommand({command:"firewall",value:actual})}trackCliCommandFlags(actual){this.trackCliCommand({command:"flags",value:actual})}trackCliCommandGit(actual){this.trackCliCommand({command:"git",value:actual})}trackCliCommandGlobalConfig(actual){this.trackCliCommand({command:"global-config",value:actual})}trackCliCommandGuidance(actual){this.trackCliCommand({command:"guidance",value:actual})}trackCliCommandHealth(actual){this.trackCliCommand({command:"health",value:actual})}trackCliCommandHelp(actual){this.trackCliCommand({command:"help",value:actual})}trackCliCommandHttpstat(actual){this.trackCliCommand({command:"httpstat",value:actual})}trackCliCommandInit(actual){this.trackCliCommand({command:"init",value:actual})}trackCliCommandTemplates(actual){this.trackCliCommand({command:"templates",value:actual})}trackCliCommandInspect(actual){this.trackCliCommand({command:"inspect",value:actual})}trackCliCommandInstall(actual){this.trackCliCommand({command:"install",value:actual})}trackCliCommandIntegration(actual){this.trackCliCommand({command:"integration",value:actual})}trackCliCommandIntegrationResource(actual){this.trackCliCommand({command:"integration-resource",value:actual})}trackCliCommandDocs(actual){this.trackCliCommand({command:"docs",value:actual})}trackCliCommandKb(actual){this.trackCliCommand({command:"kb",value:actual})}trackCliCommandKms(actual){this.trackCliCommand({command:"kms",value:actual})}trackCliCommandLink(actual){this.trackCliCommand({command:"link",value:actual})}trackCliCommandList(actual){this.trackCliCommand({command:"list",value:actual})}trackCliCommandLogin(actual){this.trackCliCommand({command:"login",value:actual})}trackCliCommandLogout(actual){this.trackCliCommand({command:"logout",value:actual})}trackCliCommandLogs(actual){this.trackCliCommand({command:"logs",value:actual})}trackCliCommandMetrics(actual){this.trackCliCommand({command:"metrics",value:actual})}trackCliCommandMicrofrontends(actual){this.trackCliCommand({command:"microfrontends",value:actual})}trackCliCommandMonitors(actual){this.trackCliCommand({command:"monitors",value:actual})}trackCliCommandOpen(actual){this.trackCliCommand({command:"open",value:actual})}trackCliCommandPageIntegrity(actual){this.trackCliCommand({command:"page-integrity",value:actual})}trackCliCommandFeedback(actual){this.trackCliCommand({command:"feedback",value:actual})}trackCliCommandPricing(actual){this.trackCliCommand({command:"pricing",value:actual})}trackCliCommandProject(actual){this.trackCliCommand({command:"project",value:actual})}trackCliCommandPromote(actual){this.trackCliCommand({command:"promote",value:actual})}trackCliCommandPull(actual){this.trackCliCommand({command:"pull",value:actual})}trackCliCommandRollback(actual){this.trackCliCommand({command:"rollback",value:actual})}trackCliCommandRollingRelease(actual){this.trackCliCommand({command:"rolling-release",value:actual})}trackCliCommandRedeploy(actual){this.trackCliCommand({command:"redeploy",value:actual})}trackCliCommandRedirects(actual){this.trackCliCommand({command:"redirects",value:actual})}trackCliCommandRoutes(actual){this.trackCliCommand({command:"routes",value:actual})}trackCliCommandRemove(actual){this.trackCliCommand({command:"remove",value:actual})}trackCliCommandSignup(actual){this.trackCliCommand({command:"signup",value:actual})}trackCliCommandSkills(actual){this.trackCliCommand({command:"skills",value:actual})}trackCliCommandSetup(actual){this.trackCliCommand({command:"setup",value:actual})}trackCliCommandSandbox(actual){this.trackCliCommand({command:"sandbox",value:actual})}trackCliCommandSchedules(actual){this.trackCliCommand({command:"schedules",value:actual})}trackCliCommandSecurity(actual){this.trackCliCommand({command:"security",value:actual})}trackCliCommandStorage(actual){this.trackCliCommand({command:"storage",value:actual})}trackCliCommandEnvironments(actual){this.trackCliCommand({command:"environments",value:actual})}trackCliCommandTeams(actual){this.trackCliCommand({command:"teams",value:actual})}trackCliCommandOrganizations(actual){this.trackCliCommand({command:"organizations",value:actual})}trackCliCommandTokens(actual){this.trackCliCommand({command:"tokens",value:actual})}trackCliCommandTelemetry(actual){this.trackCliCommand({command:"telemetry",value:actual})}trackCliCommandTraces(actual){this.trackCliCommand({command:"traces",value:actual})}trackCliCommandWhoami(actual){this.trackCliCommand({command:"whoami",value:actual})}trackCliCommandTunnel(actual){this.trackCliCommand({command:"tunnel",value:actual})}trackCliCommandUpgrade(actual){this.trackCliCommand({command:"upgrade",value:actual})}trackCliCommandVersion(actual){this.trackCliCommand({command:"version",value:actual})}trackCliCommandWebhooks(actual){this.trackCliCommand({command:"webhooks",value:actual})}trackCliCommandUsage(actual){this.trackCliCommand({command:"usage",value:actual})}trackCliCommandVcr(actual){this.trackCliCommand({command:"vcr",value:actual})}trackCPUs(){super.trackCPUs()}trackAgenticUse(agent){super.trackAgenticUse(agent)}trackArch(){super.trackArch()}trackPlatform(){super.trackPlatform()}trackLibc(libc){super.trackLibc(libc)}trackCliLaunch(){let launch=readLaunch();launch&&this.trackLaunch(launch)}trackCIVendorName(){this.trackCI(import_ci_info.default.id)}trackStdinIsTTY(isTTY){super.trackStdinIsTTY(isTTY)}trackVersion(version){super.trackVersion(version)}trackProjectId(projectId){super.trackProjectId(projectId)}trackInvocationId(invocationId){super.trackInvocationId(invocationId)}trackDeviceId(deviceId){super.trackDeviceId(deviceId)}trackVercelPluginActiveSession(){super.trackVercelPluginActiveSession()}trackVercelPluginVersion(version){super.trackVercelPluginVersion(version)}trackErrorStatus(status){super.trackErrorStatus(status)}trackErrorCode(code){super.trackErrorCode(code)}trackErrorSlug(slug){super.trackErrorSlug(slug)}trackErrorAction(action){super.trackErrorAction(action)}trackErrorServerMessage(serverMessage){super.trackErrorServerMessage(serverMessage)}trackCliOptionCwd(cwd){cwd&&this.trackCliOption({option:"cwd",value:this.redactedValue})}trackCliOptionLocalConfig(localConfig){localConfig&&this.trackCliOption({option:"local-config",value:this.redactedValue})}trackCliOptionGlobalConfig(globalConfig){globalConfig&&this.trackCliOption({option:"global-config",value:this.redactedValue})}trackCliOptionScope(scope){scope&&this.trackCliOption({option:"scope",value:this.redactedValue})}trackCliOptionToken(token){token&&this.trackCliOption({option:"token",value:this.redactedValue})}trackCliOptionTeam(team){team&&this.trackCliOption({option:"team",value:this.redactedValue})}trackCliOptionApi(api){api&&this.trackCliOption({option:"api",value:this.redactedValue})}trackCliFlagDebug(debug){debug&&this.trackCliFlag("debug")}trackCliFlagNoColor(noColor){noColor&&this.trackCliFlag("no-color")}trackCliDeprecatedShorthands(shorthands){for(let shorthand of shorthands)this.trackDeprecatedShorthand(shorthand)}};function printCommandHelp(client,commandName,tokens){let found=findBuiltInCommand(commandName,tokens);if(!found)return;let{root}=found,target=resolveHelpTarget(root,found.tokens);return target.unknownSegment!==void 0?(printUnknownCommand(client,target.unknownSegment,[root.name,...target.typedPath]),2):target.command.dynamicHelp?void 0:(new RootTelemetryClient({opts:{store:client.telemetryEventStore}}).trackCliFlagHelp([root.name,...target.typedPath].join(":")),client.stdout.write(renderHelpTarget(target,stdoutHelp(client))),0)}function stdoutHelp(client){return{columns:client.stdout.columns??client.stderr.columns,stream:client.stdout}}function renderHelpTarget(target,destination){return help(target.command,{parent:target.parent,...destination})}function renderCommandHelp(commandName,tokens,destination){let found=findBuiltInCommand(commandName,tokens);if(!found)return;let target=resolveHelpTarget(found.root,found.tokens);return target.unknownSegment===void 0?renderHelpTarget(target,destination):void 0}function printGroupHelp(client,commandName,tokens){let found=findBuiltInCommand(commandName,tokens);if(!found)return;let{root}=found,target=resolveHelpTarget(root,found.tokens),{command}=target;if(!(target.unknownSegment!==void 0||!command.subcommands?.length||command.arguments.length>0||command.runsWithoutSubcommand||command.subcommands.some(subcommand=>subcommand.default)||command.forwardsUnknownOptions&&found.tokens.some(token=>token.startsWith("-")))){try{parseArguments([...found.tokens],getFlagsSpecification(getCommandsAlongPath(root,target.typedPath).flatMap(({options})=>options)))}catch(err){return printError(err,client),2}return client.stdout.write(renderHelpTarget(target,stdoutHelp(client))),0}}function getCommandPathOptions(commandName,tokens){let found=findBuiltInCommand(commandName,tokens);if(!found)return;let{typedPath}=resolveHelpTarget(found.root,found.tokens);return getCommandsAlongPath(found.root,typedPath).flatMap(({options})=>options)}function asksForVersion(commandName,argv){let flags;try{({flags}=parseArguments(argv.slice(2),{"--version":Boolean,"-v":Boolean},{permissive:!0}))}catch{return!1}let typedLong=flags["--version"]===!0,typedShort=flags["-v"]===!0;if(!typedLong&&!typedShort)return!1;let found=findBuiltInCommand(commandName,tokensAfterCommand(argv));if(!found)return!1;let{command,typedPath}=resolveHelpTarget(found.root,found.tokens),defaultSubcommand=command.subcommands?.find(subcommand=>subcommand.default);if(command.forwardsUnknownOptions||defaultSubcommand?.forwardsUnknownOptions)return!1;let options=getCommandsAlongPath(found.root,typedPath).flatMap(({options:options2})=>options2);defaultSubcommand&&options.push(...defaultSubcommand.options);let definesLong=options.some(option=>option.name==="version"),definesShort=definesLong||options.some(option=>option.shorthand==="v"||option.deprecatedShorthand==="v");return typedLong&&!definesLong||typedShort&&!definesShort}function deployAcceptsOptions(argv){let deploy=findBuiltInCommand("deploy",[]);if(!deploy)return!1;try{return parseArguments(argv.slice(2),getFlagsSpecification(deploy.root.options),{warnDeprecated:!1}),!0}catch{return!1}}function getCommandsAlongPath(root,typedPath){let path=[root];for(let token of typedPath){let subcommand=path[path.length-1].subcommands?.find(candidate=>candidate.name===token||candidate.aliases.includes(token));if(!subcommand)break;path.push(subcommand)}return path}var EXTERNAL_CLIS=new Set(["sandbox"]);function findBuiltInCommand(commandName,tokens){let findRoot=rootName=>commandsStructs.find(command=>command.name===rootName&&"options"in command),moved=commandName?getMovedCommand(commandName):void 0;if(moved){let[group,...path]=moved,root2=findRoot(group);return root2&&{root:root2,tokens:[...path,...tokens]}}let name=commandName?commands.get(commandName):void 0;if(!commandName||!name||EXTERNAL_CLIS.has(name))return;let root=findRoot(name);if(!root)return;let monitors=root.name==="alerts"?findRoot("monitors"):void 0;if(monitors){let alias=takeAlertsRulesAlias(root,tokens);if(alias)return{root:monitors,tokens:alias}}let namesSubcommand=commandName!==root.name&&root.subcommands?.some(subcommand=>subcommand.name===commandName||subcommand.aliases.includes(commandName));return{root,tokens:namesSubcommand?[commandName,...tokens]:tokens}}function takeAlertsRulesAlias(alerts,tokens){try{let{command,args}=takeCommand([...tokens],getFlagsSpecification(alerts.options));return command==="rules"?args:void 0}catch{return}}function printUnknownCommand(client,segment,groupPath=[]){let group=groupPath.join(" "),message=`Unknown command ${segment} for ${getCommandNamePlain(group||void 0)}.`,helpCommand2=group?`${group} --help`:"--help";if(shouldEmitNonInteractiveCommandError(client)){writeAgentError(client,{status:AGENT_STATUS.ERROR,reason:"unknown_command",message,next:[{command:getCommandNamePlain(helpCommand2),when:"See all commands"}]});return}output_manager_default.fatal(message),output_manager_default.print(`
7
+ import{commands,commandsStructs}from"./chunk-JR25PLC7.js";import{DEPRECATED_BUDGET_ACTIONS,budgetCommand}from"./chunk-GQXKF3PR.js";import{TelemetryClient,readLaunch,require_ci_info}from"./chunk-EYRBV6RM.js";import{printError}from"./chunk-HMJR6RVF.js";import{parseArguments,takeCommand}from"./chunk-INIZJZ3O.js";import{AGENT_STATUS,shouldEmitNonInteractiveCommandError,writeAgentError}from"./chunk-CSNP5RIM.js";import{getCommandNamePlain}from"./chunk-B4KA3ZH2.js";import{output_manager_default}from"./chunk-RYSO5U3E.js";import{BETA_COMMANDS,createHelpTheme,help,helpCommand,resolveHelpTarget}from"./chunk-5727HGA6.js";import{getFlagsSpecification,globalCliFlagTakesValue}from"./chunk-DORCX7UB.js";import{__toESM}from"./chunk-BZENIQ7N.js";var budgets={to:["billing","budgets"],actions:{of:budgetCommand,renamed:DEPRECATED_BUDGET_ACTIONS}},MOVED_COMMANDS={usage:{to:["billing","usage"]},budgets,budget:budgets};function getMovedCommand(name){return Object.hasOwn(MOVED_COMMANDS,name)?MOVED_COMMANDS[name].to:void 0}function allOptions(command){return[...command.options,...(command.subcommands??[]).flatMap(allOptions)]}function rewriteMovedCommand(argv){let tokens=argv.slice(2),root;try{root=takeCommand(tokens,{})}catch{return}let move=root.command&&Object.hasOwn(MOVED_COMMANDS,root.command)?MOVED_COMMANDS[root.command]:void 0;if(!(!root.command||!move)){if(move.actions){let{of,renamed}=move.actions;try{let action=takeCommand(tokens.slice(root.index+1),getFlagsSpecification(allOptions(of))),actionTo=action.command&&Object.hasOwn(renamed,action.command)?renamed[action.command]:void 0;if(actionTo){let to=[...move.to,actionTo];return argv.splice(2,tokens.length,...tokens.slice(0,root.index),...to,...action.args),{from:`${root.command} ${action.command}`,to:to.join(" ")}}}catch{}}return argv.splice(2+root.index,1,...move.to),{from:root.command,to:move.to.join(" ")}}}var import_ci_info=__toESM(require_ci_info(),1);var RootTelemetryClient=class extends TelemetryClient{trackCliExtension(){this.trackExtension()}trackCliDefaultDeploy(defaultDeploy){defaultDeploy&&this.trackDefaultDeploy()}trackCliCommandAgent(actual){this.trackCliCommand({command:"agent",value:actual})}trackCliCommandAgentRuns(actual){this.trackCliCommand({command:"agent-runs",value:actual})}trackCliCommandAiGateway(actual){this.trackCliCommand({command:"ai-gateway",value:actual})}trackCliCommandTokenPass(actual){this.trackCliCommand({command:"token-pass",value:actual})}trackCliCommandAlias(actual){this.trackCliCommand({command:"alias",value:actual})}trackCliCommandActivity(actual){this.trackCliCommand({command:"activity",value:actual})}trackCliCommandAlerts(actual){this.trackCliCommand({command:"alerts",value:actual})}trackCliCommandApi(actual){this.trackCliCommand({command:"api",value:actual})}trackCliCommandBilling(actual){this.trackCliCommand({command:"billing",value:actual})}trackCliCommandBisect(actual){this.trackCliCommand({command:"bisect",value:actual})}trackCliCommandBlob(actual){this.trackCliCommand({command:"blob",value:actual})}trackCliCommandBoard(actual){this.trackCliCommand({command:"board",value:actual})}trackCliCommandBudgets(actual){this.trackCliCommand({command:"budgets",value:actual})}trackCliCommandBuild(actual){this.trackCliCommand({command:"build",value:actual})}trackCliCommandBuy(actual){this.trackCliCommand({command:"buy",value:actual})}trackCliCommandCache(actual){this.trackCliCommand({command:"cache",value:actual})}trackCliCommandCerts(actual){this.trackCliCommand({command:"certs",value:actual})}trackCliCommandCi(actual){this.trackCliCommand({command:"ci",value:actual})}trackCliCommandChangelog(actual){this.trackCliCommand({command:"changelog",value:actual})}trackCliCommandComments(actual){this.trackCliCommand({command:"comments",value:actual})}trackCliCommandConnex(actual){this.trackCliCommand({command:"connect",value:actual})}trackCliCommandCrons(actual){this.trackCliCommand({command:"crons",value:actual})}trackCliCommandCurl(actual){this.trackCliCommand({command:"curl",value:actual})}trackCliCommandDaemons(actual){this.trackCliCommand({command:"daemons",value:actual})}trackCliCommandDrives(actual){this.trackCliCommand({command:"drives",value:actual})}trackCliCommandDeploy(actual){this.trackCliCommand({command:"deploy",value:actual})}trackCliCommandOidcPolicies(actual){this.trackCliCommand({command:"oidc-policies",value:actual})}trackCliCommandDeployHooks(actual){this.trackCliCommand({command:"deploy-hooks",value:actual})}trackCliCommandDev(actual){this.trackCliCommand({command:"dev",value:actual})}trackCliCommandDoctor(actual){this.trackCliCommand({command:"doctor",value:actual})}trackCliCommandDomains(actual){this.trackCliCommand({command:"domains",value:actual})}trackCliCommandDrains(actual){this.trackCliCommand({command:"drains",value:actual})}trackCliCommandDns(actual){this.trackCliCommand({command:"dns",value:actual})}trackCliCommandEnv(actual){this.trackCliCommand({command:"env",value:actual})}trackCliCommandExperiments(actual){this.trackCliCommand({command:"experiments",value:actual})}trackCliCommandFirewall(actual){this.trackCliCommand({command:"firewall",value:actual})}trackCliCommandFlags(actual){this.trackCliCommand({command:"flags",value:actual})}trackCliCommandGit(actual){this.trackCliCommand({command:"git",value:actual})}trackCliCommandGlobalConfig(actual){this.trackCliCommand({command:"global-config",value:actual})}trackCliCommandGuidance(actual){this.trackCliCommand({command:"guidance",value:actual})}trackCliCommandHealth(actual){this.trackCliCommand({command:"health",value:actual})}trackCliCommandHelp(actual){this.trackCliCommand({command:"help",value:actual})}trackCliCommandHttpstat(actual){this.trackCliCommand({command:"httpstat",value:actual})}trackCliCommandInit(actual){this.trackCliCommand({command:"init",value:actual})}trackCliCommandTemplates(actual){this.trackCliCommand({command:"templates",value:actual})}trackCliCommandInspect(actual){this.trackCliCommand({command:"inspect",value:actual})}trackCliCommandInstall(actual){this.trackCliCommand({command:"install",value:actual})}trackCliCommandIntegration(actual){this.trackCliCommand({command:"integration",value:actual})}trackCliCommandIntegrationResource(actual){this.trackCliCommand({command:"integration-resource",value:actual})}trackCliCommandDocs(actual){this.trackCliCommand({command:"docs",value:actual})}trackCliCommandKb(actual){this.trackCliCommand({command:"kb",value:actual})}trackCliCommandKms(actual){this.trackCliCommand({command:"kms",value:actual})}trackCliCommandLink(actual){this.trackCliCommand({command:"link",value:actual})}trackCliCommandList(actual){this.trackCliCommand({command:"list",value:actual})}trackCliCommandLogin(actual){this.trackCliCommand({command:"login",value:actual})}trackCliCommandLogout(actual){this.trackCliCommand({command:"logout",value:actual})}trackCliCommandLogs(actual){this.trackCliCommand({command:"logs",value:actual})}trackCliCommandMetrics(actual){this.trackCliCommand({command:"metrics",value:actual})}trackCliCommandMicrofrontends(actual){this.trackCliCommand({command:"microfrontends",value:actual})}trackCliCommandMonitors(actual){this.trackCliCommand({command:"monitors",value:actual})}trackCliCommandOpen(actual){this.trackCliCommand({command:"open",value:actual})}trackCliCommandPageIntegrity(actual){this.trackCliCommand({command:"page-integrity",value:actual})}trackCliCommandFeedback(actual){this.trackCliCommand({command:"feedback",value:actual})}trackCliCommandPricing(actual){this.trackCliCommand({command:"pricing",value:actual})}trackCliCommandProject(actual){this.trackCliCommand({command:"project",value:actual})}trackCliCommandPromote(actual){this.trackCliCommand({command:"promote",value:actual})}trackCliCommandPull(actual){this.trackCliCommand({command:"pull",value:actual})}trackCliCommandRollback(actual){this.trackCliCommand({command:"rollback",value:actual})}trackCliCommandRollingRelease(actual){this.trackCliCommand({command:"rolling-release",value:actual})}trackCliCommandRedeploy(actual){this.trackCliCommand({command:"redeploy",value:actual})}trackCliCommandRedirects(actual){this.trackCliCommand({command:"redirects",value:actual})}trackCliCommandRoutes(actual){this.trackCliCommand({command:"routes",value:actual})}trackCliCommandRemove(actual){this.trackCliCommand({command:"remove",value:actual})}trackCliCommandSignup(actual){this.trackCliCommand({command:"signup",value:actual})}trackCliCommandSkills(actual){this.trackCliCommand({command:"skills",value:actual})}trackCliCommandSetup(actual){this.trackCliCommand({command:"setup",value:actual})}trackCliCommandSandbox(actual){this.trackCliCommand({command:"sandbox",value:actual})}trackCliCommandSchedules(actual){this.trackCliCommand({command:"schedules",value:actual})}trackCliCommandSecurity(actual){this.trackCliCommand({command:"security",value:actual})}trackCliCommandStorage(actual){this.trackCliCommand({command:"storage",value:actual})}trackCliCommandEnvironments(actual){this.trackCliCommand({command:"environments",value:actual})}trackCliCommandTeams(actual){this.trackCliCommand({command:"teams",value:actual})}trackCliCommandOrganizations(actual){this.trackCliCommand({command:"organizations",value:actual})}trackCliCommandTokens(actual){this.trackCliCommand({command:"tokens",value:actual})}trackCliCommandTelemetry(actual){this.trackCliCommand({command:"telemetry",value:actual})}trackCliCommandTraces(actual){this.trackCliCommand({command:"traces",value:actual})}trackCliCommandWhoami(actual){this.trackCliCommand({command:"whoami",value:actual})}trackCliCommandTunnel(actual){this.trackCliCommand({command:"tunnel",value:actual})}trackCliCommandUpgrade(actual){this.trackCliCommand({command:"upgrade",value:actual})}trackCliCommandVersion(actual){this.trackCliCommand({command:"version",value:actual})}trackCliCommandWebhooks(actual){this.trackCliCommand({command:"webhooks",value:actual})}trackCliCommandUsage(actual){this.trackCliCommand({command:"usage",value:actual})}trackCliCommandVcr(actual){this.trackCliCommand({command:"vcr",value:actual})}trackCPUs(){super.trackCPUs()}trackAgenticUse(agent){super.trackAgenticUse(agent)}trackArch(){super.trackArch()}trackPlatform(){super.trackPlatform()}trackLibc(libc){super.trackLibc(libc)}trackCliLaunch(){let launch=readLaunch();launch&&this.trackLaunch(launch)}trackCIVendorName(){this.trackCI(import_ci_info.default.id)}trackStdinIsTTY(isTTY){super.trackStdinIsTTY(isTTY)}trackVersion(version){super.trackVersion(version)}trackProjectId(projectId){super.trackProjectId(projectId)}trackInvocationId(invocationId){super.trackInvocationId(invocationId)}trackDeviceId(deviceId){super.trackDeviceId(deviceId)}trackVercelPluginActiveSession(){super.trackVercelPluginActiveSession()}trackVercelPluginVersion(version){super.trackVercelPluginVersion(version)}trackErrorStatus(status){super.trackErrorStatus(status)}trackErrorCode(code){super.trackErrorCode(code)}trackErrorSlug(slug){super.trackErrorSlug(slug)}trackErrorAction(action){super.trackErrorAction(action)}trackErrorServerMessage(serverMessage){super.trackErrorServerMessage(serverMessage)}trackCliOptionCwd(cwd){cwd&&this.trackCliOption({option:"cwd",value:this.redactedValue})}trackCliOptionLocalConfig(localConfig){localConfig&&this.trackCliOption({option:"local-config",value:this.redactedValue})}trackCliOptionGlobalConfig(globalConfig){globalConfig&&this.trackCliOption({option:"global-config",value:this.redactedValue})}trackCliOptionScope(scope){scope&&this.trackCliOption({option:"scope",value:this.redactedValue})}trackCliOptionToken(token){token&&this.trackCliOption({option:"token",value:this.redactedValue})}trackCliOptionTeam(team){team&&this.trackCliOption({option:"team",value:this.redactedValue})}trackCliOptionApi(api){api&&this.trackCliOption({option:"api",value:this.redactedValue})}trackCliFlagDebug(debug){debug&&this.trackCliFlag("debug")}trackCliFlagNoColor(noColor){noColor&&this.trackCliFlag("no-color")}trackCliDeprecatedShorthands(shorthands){for(let shorthand of shorthands)this.trackDeprecatedShorthand(shorthand)}};function printCommandHelp(client,commandName,tokens){let found=findBuiltInCommand(commandName,tokens);if(!found)return;let{root}=found,target=resolveHelpTarget(root,found.tokens);return target.unknownSegment!==void 0?(printUnknownCommand(client,target.unknownSegment,[root.name,...target.typedPath]),2):target.command.dynamicHelp?void 0:(new RootTelemetryClient({opts:{store:client.telemetryEventStore}}).trackCliFlagHelp([root.name,...target.typedPath].join(":")),client.stdout.write(renderHelpTarget(target,stdoutHelp(client))),0)}function stdoutHelp(client){return{columns:client.stdout.columns??client.stderr.columns,stream:client.stdout}}function renderHelpTarget(target,destination){return help(target.command,{parent:target.parent,...destination})}function renderCommandHelp(commandName,tokens,destination){let found=findBuiltInCommand(commandName,tokens);if(!found)return;let target=resolveHelpTarget(found.root,found.tokens);return target.unknownSegment===void 0?renderHelpTarget(target,destination):void 0}function printGroupHelp(client,commandName,tokens){let found=findBuiltInCommand(commandName,tokens);if(!found)return;let{root}=found,target=resolveHelpTarget(root,found.tokens),{command}=target;if(!(target.unknownSegment!==void 0||!command.subcommands?.length||command.arguments.length>0||command.runsWithoutSubcommand||command.subcommands.some(subcommand=>subcommand.default)||command.forwardsUnknownOptions&&found.tokens.some(token=>token.startsWith("-")))){try{parseArguments([...found.tokens],getFlagsSpecification(getCommandsAlongPath(root,target.typedPath).flatMap(({options})=>options)))}catch(err){return printError(err,client),2}return client.stdout.write(renderHelpTarget(target,stdoutHelp(client))),0}}function getCommandPathOptions(commandName,tokens){let found=findBuiltInCommand(commandName,tokens);if(!found)return;let{typedPath}=resolveHelpTarget(found.root,found.tokens);return getCommandsAlongPath(found.root,typedPath).flatMap(({options})=>options)}function asksForVersion(commandName,argv){let flags;try{({flags}=parseArguments(argv.slice(2),{"--version":Boolean,"-v":Boolean},{permissive:!0}))}catch{return!1}let typedLong=flags["--version"]===!0,typedShort=flags["-v"]===!0;if(!typedLong&&!typedShort)return!1;let found=findBuiltInCommand(commandName,tokensAfterCommand(argv));if(!found)return!1;let{command,typedPath}=resolveHelpTarget(found.root,found.tokens),defaultSubcommand=command.subcommands?.find(subcommand=>subcommand.default);if(command.forwardsUnknownOptions||defaultSubcommand?.forwardsUnknownOptions)return!1;let options=getCommandsAlongPath(found.root,typedPath).flatMap(({options:options2})=>options2);defaultSubcommand&&options.push(...defaultSubcommand.options);let definesLong=options.some(option=>option.name==="version"),definesShort=definesLong||options.some(option=>option.shorthand==="v"||option.deprecatedShorthand==="v");return typedLong&&!definesLong||typedShort&&!definesShort}function deployAcceptsOptions(argv){let deploy=findBuiltInCommand("deploy",[]);if(!deploy)return!1;try{return parseArguments(argv.slice(2),getFlagsSpecification(deploy.root.options),{warnDeprecated:!1}),!0}catch{return!1}}function getCommandsAlongPath(root,typedPath){let path=[root];for(let token of typedPath){let subcommand=path[path.length-1].subcommands?.find(candidate=>candidate.name===token||candidate.aliases.includes(token));if(!subcommand)break;path.push(subcommand)}return path}var EXTERNAL_CLIS=new Set(["sandbox"]);function findBuiltInCommand(commandName,tokens){let findRoot=rootName=>commandsStructs.find(command=>command.name===rootName&&"options"in command),moved=commandName?getMovedCommand(commandName):void 0;if(moved){let[group,...path]=moved,root2=findRoot(group);return root2&&{root:root2,tokens:[...path,...tokens]}}let name=commandName?commands.get(commandName):void 0;if(!commandName||!name||EXTERNAL_CLIS.has(name))return;let root=findRoot(name);if(!root)return;let monitors=root.name==="alerts"?findRoot("monitors"):void 0;if(monitors){let alias=takeAlertsRulesAlias(root,tokens);if(alias)return{root:monitors,tokens:alias}}let namesSubcommand=commandName!==root.name&&root.subcommands?.some(subcommand=>subcommand.name===commandName||subcommand.aliases.includes(commandName));return{root,tokens:namesSubcommand?[commandName,...tokens]:tokens}}function takeAlertsRulesAlias(alerts,tokens){try{let{command,args}=takeCommand([...tokens],getFlagsSpecification(alerts.options));return command==="rules"?args:void 0}catch{return}}function printUnknownCommand(client,segment,groupPath=[]){let group=groupPath.join(" "),message=`Unknown command ${segment} for ${getCommandNamePlain(group||void 0)}.`,helpCommand2=group?`${group} --help`:"--help";if(shouldEmitNonInteractiveCommandError(client)){writeAgentError(client,{status:AGENT_STATUS.ERROR,reason:"unknown_command",message,next:[{command:getCommandNamePlain(helpCommand2),when:"See all commands"}]});return}output_manager_default.fatal(message),output_manager_default.print(`
8
8
  See all commands:
9
9
  ${helpCommand(getCommandNamePlain(helpCommand2),[],createHelpTheme(client.stderr))}
10
10
  `)}function tokensAfterCommand(argv){let args=argv.slice(2);for(let i=0;i<args.length;i++){let arg=args[i];if(arg==="--")return[];if(arg.startsWith("-")){!arg.includes("=")&&globalCliFlagTakesValue(arg)&&i++;continue}return args.slice(i+1)}return[]}function allOptions2(command){return[...command.options,...(command.subcommands??[]).flatMap(allOptions2)]}function findBetaCommand(tokens){try{let first=takeCommand(tokens,{}),name=first.command?commands.get(first.command):void 0;if(!name||BETA_COMMANDS.has(name))return name;let root=findBuiltInCommand(name,[])?.root;if(!root)return;let{command}=takeCommand(first.args,getFlagsSpecification(allOptions2(root))),subcommand=root.subcommands?.find(candidate=>candidate.name===command||command!==void 0&&candidate.aliases.includes(command)),path=subcommand&&`${root.name} ${subcommand.name}`;return path&&BETA_COMMANDS.has(path)?path:void 0}catch{return}}export{rewriteMovedCommand,RootTelemetryClient,printCommandHelp,renderCommandHelp,printGroupHelp,getCommandPathOptions,asksForVersion,deployAcceptsOptions,printUnknownCommand,tokensAfterCommand,findBetaCommand};
@@ -4,4 +4,4 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{ProjectNotFound,isAPIError}from"./chunk-GOI2VVI7.js";async function getProjectByNameOrId(client,projectNameOrId,accountId,includeRollbackInfo,fetchOptions){try{let qs=includeRollbackInfo?"?rollbackInfo=true":"";return await client.fetch(`/v9/projects/${encodeURIComponent(projectNameOrId)}${qs}`,{...fetchOptions,accountId})}catch(err){if(isAPIError(err)&&err.status===404)return new ProjectNotFound(projectNameOrId);throw err}}export{getProjectByNameOrId};
7
+ import{ProjectNotFound,isAPIError}from"./chunk-QFE3RPMA.js";async function getProjectByNameOrId(client,projectNameOrId,accountId,includeRollbackInfo,fetchOptions){try{let qs=includeRollbackInfo?"?rollbackInfo=true":"";return await client.fetch(`/v9/projects/${encodeURIComponent(projectNameOrId)}${qs}`,{...fetchOptions,accountId})}catch(err){if(isAPIError(err)&&err.status===404)return new ProjectNotFound(projectNameOrId);throw err}}export{getProjectByNameOrId};
@@ -4,4 +4,4 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{resolveProjectContext}from"./chunk-VF7XWPXA.js";function getProjectNameFromFlags(flags){return flags["--project"]}function getLinkedFlagsProject(client,projectName,options){return resolveProjectContext({client,projectNameOrId:projectName,projectNotFoundHandling:options?.projectNotFoundHandling})}export{getProjectNameFromFlags,getLinkedFlagsProject};
7
+ import{resolveProjectContext}from"./chunk-JV3YIOCO.js";function getProjectNameFromFlags(flags){return flags["--project"]}function getLinkedFlagsProject(client,projectName,options){return resolveProjectContext({client,projectNameOrId:projectName,projectNotFoundHandling:options?.projectNotFoundHandling})}export{getProjectNameFromFlags,getLinkedFlagsProject};
@@ -4,4 +4,4 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{getCommandName}from"./chunk-B4KA3ZH2.js";import{output_manager_default}from"./chunk-AP6DZGTK.js";import{require_source}from"./chunk-NB2WLB3J.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);function validateLsArgs(options){let{commandName,args,maxArgs=0,exitCode=1,usageString}=options;if(args.length>maxArgs){let usage=usageString||getCommandName(commandName);return output_manager_default.error(`Invalid number of arguments. Usage: ${import_chalk.default.cyan(usage)}`),exitCode}return 0}export{validateLsArgs};
7
+ import{getCommandName}from"./chunk-B4KA3ZH2.js";import{output_manager_default}from"./chunk-RYSO5U3E.js";import{require_source}from"./chunk-NB2WLB3J.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);function validateLsArgs(options){let{commandName,args,maxArgs=0,exitCode=1,usageString}=options;if(args.length>maxArgs){let usage=usageString||getCommandName(commandName);return output_manager_default.error(`Invalid number of arguments. Usage: ${import_chalk.default.cyan(usage)}`),exitCode}return 0}export{validateLsArgs};
@@ -4,4 +4,4 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{fetchAllPages}from"./chunk-PFOOPXTN.js";import{isPerEntityScope}from"./chunk-C35SG42R.js";import{isAPIError}from"./chunk-GOI2VVI7.js";var TEAM_BUDGET={scope:"team"},BUDGET_THRESHOLD_PERCENTS=[50,75,100],PAUSE_AT_PERCENT=100;function buildThresholds({pause,webhookUrl}){return BUDGET_THRESHOLD_PERCENTS.map(percent=>({percent,sendNotifications:!0,triggerWebhook:!!webhookUrl,pauseUsage:percent===PAUSE_AT_PERCENT?!!pause:!1}))}function thresholdsForSet({existing,pause,pauseSpecified,webhookUrl,webhookSpecified}){if(!existing?.length)return buildThresholds({pause,webhookUrl});let next=existing.map(threshold=>({...threshold}));if(pauseSpecified&&(next=applyPauseToThresholds(next,pause)),webhookSpecified){let triggerWebhook=!!webhookUrl;next=next.map(threshold=>({...threshold,triggerWebhook}))}return next}function hasPauseThreshold(thresholds){return thresholds.some(threshold=>threshold.percent===PAUSE_AT_PERCENT)}function pausePercentsOutside100(thresholds){return thresholds.filter(threshold=>threshold.pauseUsage&&threshold.percent!==PAUSE_AT_PERCENT).map(threshold=>threshold.percent)}function applyPauseToThresholds(thresholds,pause){return pause?thresholds.map(threshold=>({...threshold,pauseUsage:threshold.percent===PAUSE_AT_PERCENT})):thresholds.map(threshold=>({...threshold,pauseUsage:!1}))}function spendDollars(spend){return spend?.currentSpend==null?null:spend.currentSpend/100}function percentUsed(spent,amount){return spent!==null&&amount>0?Math.round(spent/amount*100):null}function spendPayload(spent,amount){return{currentSpend:spent,percentUsed:amount===null?null:percentUsed(spent,amount),unit:"usd"}}var NO_RETRY={retries:0};function budgetPauses(budget){return budget.thresholds.some(t=>t.pauseUsage)}function ownerJson(owner){return owner.type==="organization"?{organizationId:owner.id,organizationSlug:owner.slug}:{teamId:owner.id,teamSlug:owner.slug}}function withScopeName(item,scopeName){return Object.fromEntries(Object.entries(item).flatMap(([key,value])=>key==="scopeId"?[[key,value],["scopeName",scopeName]]:[[key,value]]))}function budgetJson(budget,scopeName){return withScopeName({...budget,webhook:budget.webhook?{id:budget.webhook.id,url:budget.webhook.url}:null},scopeName)}function budgetAlertJson(alert,scopeName){return withScopeName(alert,scopeName)}function setReceipt({owner,target,outcome,budget}){let webhookSecret=budget.webhook?.secret;return{...ownerJson(owner),target,outcome,budget:budgetJson(budget,target.name),...webhookSecret?{webhookSecret}:{}}}function removeReceipt({owner,target,budget}){return{...ownerJson(owner),target,outcome:budget?"deleted":"unchanged",alreadyAbsent:budget===null,budget:budget?budgetJson(budget,target.name):null}}function formatUsdWhole(dollars){return`$${dollars.toLocaleString("en-US",{maximumFractionDigits:0})}`}function formatUsd(dollars){return`$${dollars.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}async function listBudgets(client,selector){let budgets=await fetchAllPages(async next=>{let params=new URLSearchParams({limit:"100",status:"active"});setSelectorParams(params,selector),next&&params.set("next",next);let page=await client.fetch(`/v2/budgets?${params}`,{method:"GET",...ownerOptions(selector)});return{items:page.data??[],next:page.pagination?.next??null}});return newestPerSlot(budgets)}function newestPerSlot(budgets){let seen=new Set;return budgets.filter(budget=>{let target=isPerEntityScope(budget.scope)?budget.scopeId??"":"",slot=`${budget.ownerId}:${budget.scope}:${target}`;return seen.has(slot)?!1:(seen.add(slot),!0)})}async function findBudget(client,selector=TEAM_BUDGET){return(await listBudgets(client,selector))[0]}async function createBudget(client,input){try{return await client.fetch(`/v2/budgets${orgQuery(input)}`,{method:"POST",...ownerOptions(input),retry:{retries:0},body:{scope:input.scope,...input.scopeId?{scopeId:input.scopeId}:{},amount:input.amount,thresholds:input.thresholds,...input.webhookUrl?{webhookUrl:input.webhookUrl}:{}}})}catch(err){let budgetId=existingBudgetId(err);if(!budgetId)throw err;return updateBudget(client,budgetId,{amount:input.amount,thresholds:input.thresholds,webhookUrl:input.webhookUrl||null},input)}}function isPreviousPlanBudgetError(err){return isAPIError(err)&&err.code==="budget_not_current"}function existingBudgetId(err){if(!isAPIError(err)||err.code!=="budget_exists")return;let{budgetId,status}=err;return status==="disabled"&&typeof budgetId=="string"?budgetId:void 0}async function updateBudget(client,budgetId,input,selector){return client.fetch(budgetPath(budgetId,selector),{method:"PATCH",...ownerOptions(selector),retry:{retries:0},body:{amount:input.amount,thresholds:input.thresholds,status:"active",...input.webhookUrl!==void 0?{webhookUrl:input.webhookUrl}:{}}})}async function removeBudget(client,budgetId,selector){return client.fetch(budgetPath(budgetId,selector),{method:"DELETE",...ownerOptions(selector)})}function budgetPath(budgetId,selector){return`/v2/budgets/${encodeURIComponent(budgetId)}${orgQuery(selector)}`}async function getTeamSpend(client,teamId,selector=TEAM_BUDGET,{retry}={}){if(selector.orgId)return{currentSpend:null,avgSpend:null};let params=new URLSearchParams;selector.scope!=="team"&&setSelectorParams(params,selector);let qs=params.toString(),{data}=await client.fetch(`/teams/${encodeURIComponent(teamId)}/spend${qs?`?${qs}`:""}`,{method:"GET",...retry?{retry}:{}});return data??{currentSpend:null,avgSpend:null}}async function listBudgetAlerts(client,selector,query={},{retry}={}){let params=new URLSearchParams;setSelectorParams(params,selector);for(let[key,value]of Object.entries(query))value!==void 0&&params.set(key,String(value));let page=await client.fetch(`/v2/budget-alerts?${params}`,{method:"GET",...ownerOptions(selector),...retry?{retry}:{}});return{data:page.data??[],next:page.pagination?.next??null}}async function listBudgetProducts(client){return(await client.fetch("/v2/budget-products",{method:"GET"})).data??[]}function setSelectorParams(params,selector){if(selector){if(Array.isArray(selector.scope)){params.set("scope",selector.scope.join(","));return}params.set("scope",selector.scope),"scopeId"in selector&&selector.scopeId&&params.set("scopeId",selector.scopeId),"orgId"in selector&&selector.orgId&&params.set("orgId",selector.orgId)}}function orgIdOf(selector){return selector&&"orgId"in selector?selector.orgId:void 0}function ownerOptions(selector){return orgIdOf(selector)?{useCurrentTeam:!1}:{}}function orgQuery(selector){let orgId=orgIdOf(selector);return orgId?`?${new URLSearchParams({orgId})}`:""}export{TEAM_BUDGET,thresholdsForSet,hasPauseThreshold,pausePercentsOutside100,spendDollars,percentUsed,spendPayload,NO_RETRY,budgetPauses,ownerJson,budgetJson,budgetAlertJson,setReceipt,removeReceipt,formatUsdWhole,formatUsd,listBudgets,findBudget,createBudget,isPreviousPlanBudgetError,updateBudget,removeBudget,getTeamSpend,listBudgetAlerts,listBudgetProducts};
7
+ import{fetchAllPages}from"./chunk-7RABG6HV.js";import{isPerEntityScope}from"./chunk-GQXKF3PR.js";import{isAPIError}from"./chunk-QFE3RPMA.js";var TEAM_BUDGET={scope:"team"},BUDGET_THRESHOLD_PERCENTS=[50,75,100],PAUSE_AT_PERCENT=100;function buildThresholds({pause,webhookUrl}){return BUDGET_THRESHOLD_PERCENTS.map(percent=>({percent,sendNotifications:!0,triggerWebhook:!!webhookUrl,pauseUsage:percent===PAUSE_AT_PERCENT?!!pause:!1}))}function thresholdsForSet({existing,pause,pauseSpecified,webhookUrl,webhookSpecified}){if(!existing?.length)return buildThresholds({pause,webhookUrl});let next=existing.map(threshold=>({...threshold}));if(pauseSpecified&&(next=applyPauseToThresholds(next,pause)),webhookSpecified){let triggerWebhook=!!webhookUrl;next=next.map(threshold=>({...threshold,triggerWebhook}))}return next}function hasPauseThreshold(thresholds){return thresholds.some(threshold=>threshold.percent===PAUSE_AT_PERCENT)}function pausePercentsOutside100(thresholds){return thresholds.filter(threshold=>threshold.pauseUsage&&threshold.percent!==PAUSE_AT_PERCENT).map(threshold=>threshold.percent)}function applyPauseToThresholds(thresholds,pause){return pause?thresholds.map(threshold=>({...threshold,pauseUsage:threshold.percent===PAUSE_AT_PERCENT})):thresholds.map(threshold=>({...threshold,pauseUsage:!1}))}function spendDollars(spend){return spend?.currentSpend==null?null:spend.currentSpend/100}function percentUsed(spent,amount){return spent!==null&&amount>0?Math.round(spent/amount*100):null}function spendPayload(spent,amount){return{currentSpend:spent,percentUsed:amount===null?null:percentUsed(spent,amount),unit:"usd"}}var NO_RETRY={retries:0};function budgetPauses(budget){return budget.thresholds.some(t=>t.pauseUsage)}function ownerJson(owner){return owner.type==="organization"?{organizationId:owner.id,organizationSlug:owner.slug}:{teamId:owner.id,teamSlug:owner.slug}}function withScopeName(item,scopeName){return Object.fromEntries(Object.entries(item).flatMap(([key,value])=>key==="scopeId"?[[key,value],["scopeName",scopeName]]:[[key,value]]))}function budgetJson(budget,scopeName){return withScopeName({...budget,webhook:budget.webhook?{id:budget.webhook.id,url:budget.webhook.url}:null},scopeName)}function budgetAlertJson(alert,scopeName){return withScopeName(alert,scopeName)}function setReceipt({owner,target,outcome,budget}){let webhookSecret=budget.webhook?.secret;return{...ownerJson(owner),target,outcome,budget:budgetJson(budget,target.name),...webhookSecret?{webhookSecret}:{}}}function removeReceipt({owner,target,budget}){return{...ownerJson(owner),target,outcome:budget?"deleted":"unchanged",alreadyAbsent:budget===null,budget:budget?budgetJson(budget,target.name):null}}function formatUsdWhole(dollars){return`$${dollars.toLocaleString("en-US",{maximumFractionDigits:0})}`}function formatUsd(dollars){return`$${dollars.toLocaleString("en-US",{minimumFractionDigits:2,maximumFractionDigits:2})}`}async function listBudgets(client,selector){let budgets=await fetchAllPages(async next=>{let params=new URLSearchParams({limit:"100",status:"active"});setSelectorParams(params,selector),next&&params.set("next",next);let page=await client.fetch(`/v2/budgets?${params}`,{method:"GET",...ownerOptions(selector)});return{items:page.data??[],next:page.pagination?.next??null}});return newestPerSlot(budgets)}function newestPerSlot(budgets){let seen=new Set;return budgets.filter(budget=>{let target=isPerEntityScope(budget.scope)?budget.scopeId??"":"",slot=`${budget.ownerId}:${budget.scope}:${target}`;return seen.has(slot)?!1:(seen.add(slot),!0)})}async function findBudget(client,selector=TEAM_BUDGET){return(await listBudgets(client,selector))[0]}async function createBudget(client,input){try{return await client.fetch(`/v2/budgets${orgQuery(input)}`,{method:"POST",...ownerOptions(input),retry:{retries:0},body:{scope:input.scope,...input.scopeId?{scopeId:input.scopeId}:{},amount:input.amount,thresholds:input.thresholds,...input.webhookUrl?{webhookUrl:input.webhookUrl}:{}}})}catch(err){let budgetId=existingBudgetId(err);if(!budgetId)throw err;return updateBudget(client,budgetId,{amount:input.amount,thresholds:input.thresholds,webhookUrl:input.webhookUrl||null},input)}}function isPreviousPlanBudgetError(err){return isAPIError(err)&&err.code==="budget_not_current"}function existingBudgetId(err){if(!isAPIError(err)||err.code!=="budget_exists")return;let{budgetId,status}=err;return status==="disabled"&&typeof budgetId=="string"?budgetId:void 0}async function updateBudget(client,budgetId,input,selector){return client.fetch(budgetPath(budgetId,selector),{method:"PATCH",...ownerOptions(selector),retry:{retries:0},body:{amount:input.amount,thresholds:input.thresholds,status:"active",...input.webhookUrl!==void 0?{webhookUrl:input.webhookUrl}:{}}})}async function removeBudget(client,budgetId,selector){return client.fetch(budgetPath(budgetId,selector),{method:"DELETE",...ownerOptions(selector)})}function budgetPath(budgetId,selector){return`/v2/budgets/${encodeURIComponent(budgetId)}${orgQuery(selector)}`}async function getTeamSpend(client,teamId,selector=TEAM_BUDGET,{retry}={}){if(selector.orgId){let params2=new URLSearchParams({scope:selector.scope,include:"current"}),{data:data2}=await client.fetch(`/v2/organizations/${encodeURIComponent(selector.orgId)}/budget-spend?${params2}`,{method:"GET",...ownerOptions(selector),...retry?{retry}:{}});return data2??{currentSpend:null,avgSpend:null}}let params=new URLSearchParams;selector.scope!=="team"&&setSelectorParams(params,selector),params.set("include","current");let{data}=await client.fetch(`/teams/${encodeURIComponent(teamId)}/spend?${params}`,{method:"GET",...retry?{retry}:{}});return data??{currentSpend:null,avgSpend:null}}async function listBudgetAlerts(client,selector,query={},{retry}={}){let params=new URLSearchParams;setSelectorParams(params,selector);for(let[key,value]of Object.entries(query))value!==void 0&&params.set(key,String(value));let page=await client.fetch(`/v2/budget-alerts?${params}`,{method:"GET",...ownerOptions(selector),...retry?{retry}:{}});return{data:page.data??[],next:page.pagination?.next??null}}async function listBudgetProducts(client){return(await client.fetch("/v2/budget-products",{method:"GET"})).data??[]}function setSelectorParams(params,selector){if(selector){if(Array.isArray(selector.scope)){params.set("scope",selector.scope.join(","));return}params.set("scope",selector.scope),"scopeId"in selector&&selector.scopeId&&params.set("scopeId",selector.scopeId),"orgId"in selector&&selector.orgId&&params.set("orgId",selector.orgId)}}function orgIdOf(selector){return selector&&"orgId"in selector?selector.orgId:void 0}function ownerOptions(selector){return orgIdOf(selector)?{useCurrentTeam:!1}:{}}function orgQuery(selector){let orgId=orgIdOf(selector);return orgId?`?${new URLSearchParams({orgId})}`:""}export{TEAM_BUDGET,thresholdsForSet,hasPauseThreshold,pausePercentsOutside100,spendDollars,percentUsed,spendPayload,NO_RETRY,budgetPauses,ownerJson,budgetJson,budgetAlertJson,setReceipt,removeReceipt,formatUsdWhole,formatUsd,listBudgets,findBudget,createBudget,isPreviousPlanBudgetError,updateBudget,removeBudget,getTeamSpend,listBudgetAlerts,listBudgetProducts};
@@ -4,6 +4,6 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{getExitCodeForErrorCode}from"./chunk-ZJNDLFZ7.js";import{isJSONObject}from"./chunk-Z2KANBOU.js";import{AGENT_REASON,buildCommandWithGlobalFlags,getExitCodeForReason,outputAgentError}from"./chunk-4SS6W6JK.js";import{output_manager_default}from"./chunk-AP6DZGTK.js";import{readFileSync}from"fs";import{resolve}from"path";var MONITORS_API={basePath:"/alerts/v3/monitors",itemKey:"monitor",listKey:"monitors",typesKey:"monitorTypes",idKey:"monitorId"},ALERT_RULES_API={basePath:"/alerts/v3/alert-rules",itemKey:"rule",listKey:"rules",typesKey:"ruleTypes",idKey:"ruleId"};function rulesCollectionPath(api,teamId,options={}){let query=new URLSearchParams({teamId});return options.limit!==void 0&&query.set("limit",String(options.limit)),options.cursor&&query.set("cursor",options.cursor),options.projectId&&query.set("projectId",options.projectId),options.type&&query.set("type",options.type),`${api.basePath}?${query.toString()}`}function rulesItemPath(api,teamId,ruleId){let query=new URLSearchParams({teamId});return`${api.basePath}/${encodeURIComponent(ruleId)}?${query.toString()}`}function ruleNotificationsPath(api,teamId,ruleId){let query=new URLSearchParams({teamId});return`${api.basePath}/${encodeURIComponent(ruleId)}/notifications?${query.toString()}`}function rulesNotificationsPath(api,teamId,options={}){let query=new URLSearchParams({teamId});return options.limit!==void 0&&query.set("limit",String(options.limit)),options.cursor&&query.set("cursor",options.cursor),`${api.basePath}/notifications?${query.toString()}`}function rulesNotificationLinksPath(api,teamId,ruleId){let query=new URLSearchParams({teamId});return`${api.basePath}/${encodeURIComponent(ruleId)}/notifications/links?${query.toString()}`}function rulesSchemaPath(api,teamId,type){let query=new URLSearchParams({teamId});return type&&query.set("type",type),`${api.basePath}/schema?${query.toString()}`}async function fetchRule(client,api,scope,ruleId){return(await client.fetch(rulesItemPath(api,scope.teamId,ruleId)))[api.itemKey]}function getIssues(error){return Array.isArray(error.issues)?error.issues.filter(issue=>isJSONObject(issue)&&typeof issue.path=="string"&&typeof issue.message=="string"):[]}function outputRulesError(client,jsonOutput,code,message,options={}){let issues=options.issues??[],issueSummary=issues.slice(0,5).map(issue=>`${issue.path||"body"}: ${issue.message}`).join("; "),exitCode=options.reason!==void 0?getExitCodeForReason(options.reason):getExitCodeForErrorCode(code);return outputAgentError(client,{status:"error",reason:options.reason??AGENT_REASON.INVALID_ARGUMENTS,message,hint:options.hint??(issueSummary||void 0)},exitCode),jsonOutput?client.stdout.write(`${JSON.stringify({error:{code,message,...issues.length?{issues}:{}}},null,2)}
7
+ import{getExitCodeForErrorCode}from"./chunk-OOPF73RV.js";import{isJSONObject}from"./chunk-4Z6R5KHZ.js";import{AGENT_REASON,buildCommandWithGlobalFlags,getExitCodeForReason,outputAgentError}from"./chunk-CSNP5RIM.js";import{output_manager_default}from"./chunk-RYSO5U3E.js";import{readFileSync}from"fs";import{resolve}from"path";var MONITORS_API={basePath:"/alerts/v3/monitors",itemKey:"monitor",listKey:"monitors",typesKey:"monitorTypes",idKey:"monitorId"},ALERT_RULES_API={basePath:"/alerts/v3/alert-rules",itemKey:"rule",listKey:"rules",typesKey:"ruleTypes",idKey:"ruleId"};function rulesCollectionPath(api,teamId,options={}){let query=new URLSearchParams({teamId});return options.limit!==void 0&&query.set("limit",String(options.limit)),options.cursor&&query.set("cursor",options.cursor),options.projectId&&query.set("projectId",options.projectId),options.type&&query.set("type",options.type),`${api.basePath}?${query.toString()}`}function rulesItemPath(api,teamId,ruleId){let query=new URLSearchParams({teamId});return`${api.basePath}/${encodeURIComponent(ruleId)}?${query.toString()}`}function ruleNotificationsPath(api,teamId,ruleId){let query=new URLSearchParams({teamId});return`${api.basePath}/${encodeURIComponent(ruleId)}/notifications?${query.toString()}`}function rulesNotificationsPath(api,teamId,options={}){let query=new URLSearchParams({teamId});return options.limit!==void 0&&query.set("limit",String(options.limit)),options.cursor&&query.set("cursor",options.cursor),`${api.basePath}/notifications?${query.toString()}`}function rulesNotificationLinksPath(api,teamId,ruleId){let query=new URLSearchParams({teamId});return`${api.basePath}/${encodeURIComponent(ruleId)}/notifications/links?${query.toString()}`}function rulesSchemaPath(api,teamId,type){let query=new URLSearchParams({teamId});return type&&query.set("type",type),`${api.basePath}/schema?${query.toString()}`}async function fetchRule(client,api,scope,ruleId){return(await client.fetch(rulesItemPath(api,scope.teamId,ruleId)))[api.itemKey]}function getIssues(error){return Array.isArray(error.issues)?error.issues.filter(issue=>isJSONObject(issue)&&typeof issue.path=="string"&&typeof issue.message=="string"):[]}function outputRulesError(client,jsonOutput,code,message,options={}){let issues=options.issues??[],issueSummary=issues.slice(0,5).map(issue=>`${issue.path||"body"}: ${issue.message}`).join("; "),exitCode=options.reason!==void 0?getExitCodeForReason(options.reason):getExitCodeForErrorCode(code);return outputAgentError(client,{status:"error",reason:options.reason??AGENT_REASON.INVALID_ARGUMENTS,message,hint:options.hint??(issueSummary||void 0)},exitCode),jsonOutput?client.stdout.write(`${JSON.stringify({error:{code,message,...issues.length?{issues}:{}}},null,2)}
8
8
  `):output_manager_default.fatal([message,...issues.map(issue=>` ${issue.path}: ${issue.message}`)].join(`
9
9
  `)),exitCode}function handleRulesApiError(client,err,jsonOutput){let message=err.status===401?"You do not have access to monitors in this team. Ensure your role can manage Alert Rules, or pass --token and --scope.":err.status===403?err.serverMessage||"You do not have permission to manage monitors in this team.":err.status>=500?`The monitors endpoint failed (${err.status}). Re-run with --debug and share the x-vercel-id from the failed request.`:err.serverMessage||`API error (${err.status}).`;return outputRulesError(client,jsonOutput,err.code||"API_ERROR",message,{reason:err.status===401?"not_authorized":err.status===403?"forbidden":err.status===404?AGENT_REASON.NOT_FOUND:err.status===429?"rate_limited":AGENT_REASON.API_ERROR,issues:getIssues(err),hint:err.status===401||err.status===403?"Confirm the team with `vercel whoami`; use --scope <team-slug> if the monitor belongs to another team.":void 0})}var LEGACY_BODY_FIELDS=["alertTypes","customAlert","queryJsonString"];function readRuleBody(client,bodyPath,jsonOutput){let raw;try{raw=readFileSync(resolve(client.cwd,bodyPath),"utf8")}catch{return outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS",`Could not read --body file: ${bodyPath}`)}let parsed;try{parsed=JSON.parse(raw)}catch{return outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS","Invalid JSON in --body file.")}return isJSONObject(parsed)?LEGACY_BODY_FIELDS.some(field=>Object.hasOwn(parsed,field))?outputRulesError(client,jsonOutput,"LEGACY_ALERT_RULE_BODY","This body uses the previous alert-rules shape. Rewrite it using the current schema.",{hint:"Run `vercel monitors schema --type built-in` for examples."}):parsed:outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS","The --body file must contain a JSON object.")}function getBodyType(body){return body.type==="built-in"||body.type==="custom"?body.type:void 0}function emitRulesArgParseError(client,err,recoverWithProjectFlag){let message=err instanceof Error?err.message:String(err),projectFlagMissingArg=message.includes("--project")&&message.includes("requires argument");outputAgentError(client,{status:"error",reason:AGENT_REASON.INVALID_ARGUMENTS,message:projectFlagMissingArg?"`--project` requires a project name or id (for example `--project my-app`).":message,next:[{command:buildCommandWithGlobalFlags(client.argv,projectFlagMissingArg?recoverWithProjectFlag:"monitors --help"),when:projectFlagMissingArg?"Retry with a project name or id":"See valid `monitors` subcommands"}]},2)}export{MONITORS_API,ALERT_RULES_API,rulesCollectionPath,rulesItemPath,ruleNotificationsPath,rulesNotificationsPath,rulesNotificationLinksPath,rulesSchemaPath,fetchRule,outputRulesError,handleRulesApiError,readRuleBody,getBodyType,emitRulesArgParseError};
@@ -4,6 +4,6 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{RULE_ENVIRONMENTS}from"./chunk-PIDEH4SJ.js";import{AGENT_STATUS}from"./chunk-4SS6W6JK.js";import{warnDeprecatedInput}from"./chunk-FEJD7MRH.js";function writeConfigJson(client,{project,bare,envelope,message,next}){if(!client.nonInteractive){client.stdout.write(`${JSON.stringify(bare,null,2)}
7
+ import{RULE_ENVIRONMENTS}from"./chunk-T44RB754.js";import{AGENT_STATUS}from"./chunk-CSNP5RIM.js";import{warnDeprecatedInput}from"./chunk-KA2KG3SY.js";function writeConfigJson(client,{project,bare,envelope,message,next}){if(!client.nonInteractive){client.stdout.write(`${JSON.stringify(bare,null,2)}
8
8
  `);return}client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.OK,projectId:project.id,projectName:project.name,...envelope,message,next},null,2)}
9
9
  `)}var RULE_LIMIT=10,MIN_SAMPLE_RATE=1,MAX_SAMPLE_RATE=100;function isRuleEnvironment(value){return RULE_ENVIRONMENTS.includes(value)}var ENVIRONMENT_ERROR=`\`environment\` must be one of: ${RULE_ENVIRONMENTS.join(", ")}.`,RATE_ERROR=`\`rate\` must be a whole number from ${MIN_SAMPLE_RATE} to ${MAX_SAMPLE_RATE}.`,EMPTY_PATH_ERROR="`requestPath` cannot be empty.";function parseSampleRate(value){if(!/^\d+$/.test(value.trim()))return;let rate=Number(value);return rate>=MIN_SAMPLE_RATE&&rate<=MAX_SAMPLE_RATE?rate:void 0}function toRow(rule){return{environment:rule.env??"any",requestPath:rule.requestPath??null,sampleRate:Math.round(rule.rate*100)}}function toApiRate(sampleRate){return sampleRate/100}function toRule(row){return{type:"head_sampling",rate:toApiRate(row.sampleRate),...row.environment==="any"?{}:{env:row.environment},...row.requestPath===null?{}:{requestPath:row.requestPath}}}var ALL_PATHS_LABEL="(all paths)";function formatPath(requestPath){return requestPath??ALL_PATHS_LABEL}function formatRate(sampleRate){return`${sampleRate}%`}function formatRuleTarget(environment,requestPath){return`${environment} ${formatPath(requestPath)}`}function formatRuleLine(row){return`${formatRuleTarget(row.environment,row.requestPath)} ${formatRate(row.sampleRate)}`}var COMMAND_WORD_COUNT=3;function subcommandArguments(positional){return positional.slice(COMMAND_WORD_COUNT)}function resolveRuleEnvironment(client,environmentFlag,args){if(environmentFlag===void 0){let[environment,...rest]=args;return environment!==void 0&&isRuleEnvironment(environment)?(warnDeprecatedInput(client,"The environment argument","--environment"),{environment,args:rest}):{environment:void 0,args}}return args[0]!==void 0&&isRuleEnvironment(args[0])?{error:"Can't use an environment argument with --environment. Use --environment."}:{environment:environmentFlag,args}}function hasSameKey(a,b){return a.environment===b.environment&&a.requestPath===b.requestPath}async function readTracingConfig({client,teamId,projectId,projectName}){let config=await client.fetch(`/v1/drains/tracing/config?${new URLSearchParams({projectId})}`,{accountId:teamId}),sampling=config.enabled&&config.sampling.length===0?[{type:"head_sampling",rate:1}]:config.sampling;return{project:{id:projectId,name:projectName},enabled:config.enabled,entries:sampling.map(rule=>({rule,row:toRow(rule)}))}}async function writeSamplingRules({client,teamId,projectId,rules}){await client.fetch(`/v1/drains/tracing/config?${new URLSearchParams({projectId})}`,{accountId:teamId,method:"PUT",body:{enabled:rules.length>0,...rules.length>0?{sampling:rules}:{}}})}export{writeConfigJson,RULE_LIMIT,isRuleEnvironment,ENVIRONMENT_ERROR,RATE_ERROR,EMPTY_PATH_ERROR,parseSampleRate,toApiRate,toRule,formatPath,formatRate,formatRuleTarget,formatRuleLine,subcommandArguments,resolveRuleEnvironment,hasSameKey,readTracingConfig,writeSamplingRules};