@vercel/cli-support 66.4.0 → 66.5.0-snapshot-f10b9946b10d

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 (278) hide show
  1. package/dist/chunks/add-563RV6JX.js +8 -0
  2. package/dist/chunks/add-HRB6XY33.js +8 -0
  3. package/dist/chunks/add-IUTGTBA4.js +8 -0
  4. package/dist/chunks/alerts-CIQQJC4S.js +8 -0
  5. package/dist/chunks/build-OMIYCGMR.js +7 -0
  6. package/dist/chunks/{chunk-FHMMYUAF.js → chunk-2AU6O6Z5.js} +1 -1
  7. package/dist/chunks/{chunk-VNY6WA2E.js → chunk-2D5PTFAY.js} +1 -1
  8. package/dist/chunks/{chunk-AJGLWQWP.js → chunk-2G2SALNN.js} +1 -1
  9. package/dist/chunks/{chunk-XRPGN3XZ.js → chunk-2OMI3IUW.js} +1 -1
  10. package/dist/chunks/{chunk-4ZIJL4U6.js → chunk-2RRZCRWX.js} +1 -1
  11. package/dist/chunks/{chunk-TPMBWSAM.js → chunk-33HVDSWP.js} +1 -1
  12. package/dist/chunks/{chunk-E3FOLLEC.js → chunk-3A3GU62R.js} +1 -1
  13. package/dist/chunks/{chunk-CFQPIYKY.js → chunk-3OZCZF4N.js} +1 -1
  14. package/dist/chunks/chunk-4SS6W6JK.js +11 -0
  15. package/dist/chunks/{chunk-6PAJ6GJK.js → chunk-5J4E2W4F.js} +1 -1
  16. package/dist/chunks/{chunk-AZZLV7WI.js → chunk-5O4AXCN7.js} +1 -1
  17. package/dist/chunks/{chunk-K5AHCH2B.js → chunk-6GE4V7MW.js} +1 -1
  18. package/dist/chunks/{chunk-J4ET2U4J.js → chunk-6PDKIOAO.js} +1 -1
  19. package/dist/chunks/{chunk-A7E3EGDM.js → chunk-76DSBD4X.js} +1 -1
  20. package/dist/chunks/{chunk-LKQACPVL.js → chunk-7AVHDJSP.js} +4 -4
  21. package/dist/chunks/{chunk-LD7EQJRG.js → chunk-7W565DJB.js} +1 -1
  22. package/dist/chunks/{chunk-5NLEENEL.js → chunk-ACN6DBTC.js} +1 -1
  23. package/dist/chunks/{chunk-CMHY2UFZ.js → chunk-AFHZC47H.js} +1 -1
  24. package/dist/chunks/{chunk-6JJ6MZW2.js → chunk-AIXEVICT.js} +1 -1
  25. package/dist/chunks/{chunk-O42P2UDX.js → chunk-BCAI7MED.js} +1 -1
  26. package/dist/chunks/{chunk-NKWA7NQP.js → chunk-C335SWOB.js} +1 -1
  27. package/dist/chunks/{chunk-LYL26S3N.js → chunk-CINNNQDJ.js} +1 -1
  28. package/dist/chunks/{chunk-TBWFT22U.js → chunk-CSCUVSJM.js} +1 -1
  29. package/dist/chunks/{chunk-ZKQ47ZXI.js → chunk-D2E4COIY.js} +1 -1
  30. package/dist/chunks/{chunk-OMG2DOCL.js → chunk-D2TVI7KK.js} +1 -1
  31. package/dist/chunks/{chunk-QHICDCEC.js → chunk-DEM66DOY.js} +1 -1
  32. package/dist/chunks/{chunk-JWKFVECK.js → chunk-DHKWTBF6.js} +1 -1
  33. package/dist/chunks/{chunk-Y2FVJ7YO.js → chunk-DOMBKOLJ.js} +1 -1
  34. package/dist/chunks/{chunk-BKVGBXIF.js → chunk-DZ77BIEV.js} +1 -1
  35. package/dist/chunks/{chunk-YSZREQZD.js → chunk-E4VPDMRQ.js} +1 -1
  36. package/dist/chunks/{chunk-5NMD7U2W.js → chunk-EAQAV7UZ.js} +1 -1
  37. package/dist/chunks/{chunk-YVL744ZH.js → chunk-EFFJUYYS.js} +2 -2
  38. package/dist/chunks/chunk-EFP3LK4G.js +8 -0
  39. package/dist/chunks/{chunk-IG5ACFU6.js → chunk-F4UEGELU.js} +1 -1
  40. package/dist/chunks/chunk-FEJD7MRH.js +7 -0
  41. package/dist/chunks/{chunk-I27PMO5P.js → chunk-FFN3EGSF.js} +1 -1
  42. package/dist/chunks/{chunk-OA27OSXW.js → chunk-FOFX7LHS.js} +1 -1
  43. package/dist/chunks/{chunk-JVSU3BY3.js → chunk-GB2ZWZQU.js} +1 -1
  44. package/dist/chunks/{chunk-WYD4BH6D.js → chunk-GUGP6OY2.js} +1 -1
  45. package/dist/chunks/{chunk-W4IW6A54.js → chunk-GYUNOFDD.js} +2 -2
  46. package/dist/chunks/{chunk-NMCZ5PDO.js → chunk-H2KNSYPR.js} +1 -1
  47. package/dist/chunks/{chunk-6LXXO6WG.js → chunk-IF6GA273.js} +1 -1
  48. package/dist/chunks/{chunk-L5APBYTA.js → chunk-JBYROCAC.js} +1 -1
  49. package/dist/chunks/chunk-K3MGQQEP.js +7 -0
  50. package/dist/chunks/{chunk-QXM4CNRK.js → chunk-KLYFOXYH.js} +1 -1
  51. package/dist/chunks/{chunk-MUTGN6EZ.js → chunk-KQ6X77WP.js} +1 -1
  52. package/dist/chunks/{chunk-2RCMLZIT.js → chunk-KRP4EMD2.js} +1 -1
  53. package/dist/chunks/{chunk-DMZLFZBX.js → chunk-KSGN5OCV.js} +1 -1
  54. package/dist/chunks/{chunk-6YGECVLI.js → chunk-L5PIUIUM.js} +1 -1
  55. package/dist/chunks/{chunk-HAGBKLAS.js → chunk-LNZEYUEC.js} +1 -1
  56. package/dist/chunks/chunk-MINTHN6C.js +7 -0
  57. package/dist/chunks/chunk-N6JHFCWC.js +7 -0
  58. package/dist/chunks/chunk-NLK7NGVP.js +7 -0
  59. package/dist/chunks/{chunk-SSNOY4RM.js → chunk-O7GNYVVM.js} +1 -1
  60. package/dist/chunks/{chunk-25B7DCD6.js → chunk-OE26EQSH.js} +1 -1
  61. package/dist/chunks/{chunk-S3RJKATD.js → chunk-OF32Z3UP.js} +1 -1
  62. package/dist/chunks/{chunk-4F2PK7MV.js → chunk-OISNKAC6.js} +1 -1
  63. package/dist/chunks/{chunk-Y3AAO2UW.js → chunk-OXS5VO4X.js} +1 -1
  64. package/dist/chunks/{chunk-D44WCAOX.js → chunk-PFOOPXTN.js} +2 -2
  65. package/dist/chunks/{chunk-YIL6OD24.js → chunk-PKR32I2N.js} +1 -1
  66. package/dist/chunks/{chunk-CO3S5MFZ.js → chunk-QGHAD5A5.js} +1 -1
  67. package/dist/chunks/{chunk-CYCIBBJ3.js → chunk-QRG24GJG.js} +1 -1
  68. package/dist/chunks/{chunk-VVSRVQJQ.js → chunk-QZJOKECY.js} +1 -1
  69. package/dist/chunks/{chunk-4222KNIU.js → chunk-QZKRVE44.js} +2 -2
  70. package/dist/chunks/{chunk-DT5HQUJV.js → chunk-R33HJGYA.js} +1 -1
  71. package/dist/chunks/{chunk-GVW4NA3F.js → chunk-RBW62SOU.js} +1 -1
  72. package/dist/chunks/chunk-RDDIWY3O.js +10 -0
  73. package/dist/chunks/{chunk-PY4WWD6Z.js → chunk-RVIJRFVD.js} +1 -1
  74. package/dist/chunks/{chunk-22XQ3FQJ.js → chunk-S4AANAHX.js} +1 -1
  75. package/dist/chunks/{chunk-M3Y63BLW.js → chunk-SPVOJ3HW.js} +1 -1
  76. package/dist/chunks/{chunk-JCCDHR3I.js → chunk-SQCVI2EG.js} +1 -1
  77. package/dist/chunks/{chunk-GAS6EYQH.js → chunk-SXW2G4WD.js} +2 -2
  78. package/dist/chunks/{chunk-7CAXN2PV.js → chunk-SYVWRGFQ.js} +1 -1
  79. package/dist/chunks/{chunk-D7FX3KQX.js → chunk-TC4E2TFA.js} +1 -1
  80. package/dist/chunks/chunk-TNQUCTJH.js +24 -0
  81. package/dist/chunks/{chunk-SZO73QV5.js → chunk-TSNRTRIM.js} +1 -1
  82. package/dist/chunks/{chunk-7HLAWGY2.js → chunk-UG3FZ5Q7.js} +1 -1
  83. package/dist/chunks/chunk-VF7XWPXA.js +7 -0
  84. package/dist/chunks/{chunk-AMOI3EAW.js → chunk-VPSR2O55.js} +4 -4
  85. package/dist/chunks/{chunk-7RPBEXKZ.js → chunk-VUUU4KDL.js} +1 -1
  86. package/dist/chunks/{chunk-BPIGFKNN.js → chunk-VZ4URN3U.js} +1 -1
  87. package/dist/chunks/{chunk-IF644EL7.js → chunk-W2L24GM7.js} +1 -1
  88. package/dist/chunks/{chunk-XUTUL2RN.js → chunk-WAFBTC45.js} +1 -1
  89. package/dist/chunks/{chunk-ZK4NRNJ2.js → chunk-WIF4VGYZ.js} +1 -1
  90. package/dist/chunks/{chunk-AG3KGTVM.js → chunk-X47GV5HM.js} +1 -1
  91. package/dist/chunks/{chunk-UE3YVFFX.js → chunk-X7KKWUPS.js} +1 -1
  92. package/dist/chunks/{chunk-CJXPUSBO.js → chunk-XAGG5BJT.js} +1 -1
  93. package/dist/chunks/{chunk-ZD4H7IUH.js → chunk-XBHAU2M3.js} +1 -1
  94. package/dist/chunks/{chunk-NWFONVGV.js → chunk-XDWAUOFO.js} +1 -1
  95. package/dist/chunks/{chunk-WW44HSPU.js → chunk-Y4J4STZV.js} +1 -1
  96. package/dist/chunks/{chunk-TCHR65QZ.js → chunk-Y77DXGGN.js} +1 -1
  97. package/dist/chunks/{chunk-26ZLTV7O.js → chunk-YI7NKOCU.js} +2 -2
  98. package/dist/chunks/{chunk-FLFZVZBL.js → chunk-YLLFLPNA.js} +1 -1
  99. package/dist/chunks/{chunk-TUTCJ7CX.js → chunk-YOAQNRBN.js} +1 -1
  100. package/dist/chunks/{chunk-IBZJP22D.js → chunk-Z2KANBOU.js} +34 -34
  101. package/dist/chunks/{chunk-U4J3IR2U.js → chunk-Z7WZVEPP.js} +1 -1
  102. package/dist/chunks/{chunk-B4PBNKLU.js → chunk-ZA5O22ZY.js} +1 -1
  103. package/dist/chunks/{chunk-LYBSCCZL.js → chunk-ZSGNLAAJ.js} +1 -1
  104. package/dist/chunks/clear-TH6G33QK.js +8 -0
  105. package/dist/chunks/{compile-vercel-config-TW77XH2J.js → compile-vercel-config-24IXPM4W.js} +1 -1
  106. package/dist/chunks/config-2SBML7OY.js +8 -0
  107. package/dist/chunks/config-ZSE26DSM.js +7 -0
  108. package/dist/chunks/{contract-3IQOORDY.js → contract-BLCQGFZK.js} +1 -1
  109. package/dist/chunks/delete-RGHXL4JH.js +9 -0
  110. package/dist/chunks/delete-ZV4SHUTR.js +10 -0
  111. package/dist/chunks/{describe-RRUINYLN.js → describe-442UUQIF.js} +1 -1
  112. package/dist/chunks/{detect-projects-WO6GTQRY.js → detect-projects-NBZSMQ5C.js} +1 -1
  113. package/dist/chunks/{detect-services-GQO6QEXB.js → detect-services-CRZW6FKM.js} +1 -1
  114. package/dist/chunks/disable-MYGA6HVS.js +7 -0
  115. package/dist/chunks/discard-I5TKYCDJ.js +14 -0
  116. package/dist/chunks/edit-KGCUTTOZ.js +8 -0
  117. package/dist/chunks/edit-ZRNGGRVL.js +9 -0
  118. package/dist/chunks/enable-NODSFDKF.js +7 -0
  119. package/dist/chunks/{export-JVDQWEFD.js → export-TOSUN6JO.js} +1 -1
  120. package/dist/chunks/future-RXI2OW2C.js +7 -0
  121. package/dist/chunks/generate-cert-for-deploy-7BX47IPD.js +7 -0
  122. package/dist/chunks/image-WKBQLUTQ.js +7 -0
  123. package/dist/chunks/{import-builders-3YIV3R7T.js → import-builders-I4JB6BA6.js} +1 -1
  124. package/dist/chunks/inspect-4Y2OD5MI.js +8 -0
  125. package/dist/chunks/{inspect-HUN7IHGP.js → inspect-DFYVVIJW.js} +1 -1
  126. package/dist/chunks/{inspect-PBHPRQKN.js → inspect-GBH7FAW6.js} +1 -1
  127. package/dist/chunks/inspect-STKCC3MC.js +9 -0
  128. package/dist/chunks/{inspect-6BOUR7QC.js → inspect-SX3QQUEQ.js} +1 -1
  129. package/dist/chunks/inspect-VFUV7BDM.js +13 -0
  130. package/dist/chunks/{list-WZIJ4LS3.js → list-4RRL326Z.js} +1 -1
  131. package/dist/chunks/list-6ENV2ZGG.js +12 -0
  132. package/dist/chunks/{list-TJTP6VMY.js → list-HD6KXAIG.js} +1 -1
  133. package/dist/chunks/list-MW2FV253.js +8 -0
  134. package/dist/chunks/login-O6NLJ42W.js +7 -0
  135. package/dist/chunks/login-U5VDJURN.js +9 -0
  136. package/dist/chunks/logs-X3KGHA3J.js +7 -0
  137. package/dist/chunks/ls-HRSD6VNW.js +8 -0
  138. package/dist/chunks/{ls-MRZ46D4E.js → ls-I767MTW4.js} +1 -1
  139. package/dist/chunks/ls-OLJMGFTV.js +11 -0
  140. package/dist/chunks/{ls-AH4LDLZK.js → ls-Q4WGEEBZ.js} +1 -1
  141. package/dist/chunks/{ls-FWCHBGLF.js → ls-RKOM46KV.js} +1 -1
  142. package/dist/chunks/{ls-7KTKLNDE.js → ls-TLEAYYXQ.js} +1 -1
  143. package/dist/chunks/{ls-LKOYAWGO.js → ls-VFE7PE25.js} +1 -1
  144. package/dist/chunks/{migrate-experimental-services-QUJ3Y5KW.js → migrate-experimental-services-7ZYHE5WA.js} +1 -1
  145. package/dist/chunks/mutate-BJXJON5E.js +9 -0
  146. package/dist/chunks/notifications-F3NRNUHQ.js +7 -0
  147. package/dist/chunks/open-JK42ZTLB.js +7 -0
  148. package/dist/chunks/openapi-NEYEIRF2.js +7 -0
  149. package/dist/chunks/permissions-3AQO3DCH.js +7 -0
  150. package/dist/chunks/{plugin-offer-5PC2WVPP.js → plugin-offer-NPJAEILN.js} +1 -1
  151. package/dist/chunks/prompt-missing-credentials-AHAH27TZ.js +7 -0
  152. package/dist/chunks/publish-7SCXBVZR.js +15 -0
  153. package/dist/chunks/pull-LAPD5XJG.js +7 -0
  154. package/dist/chunks/purchase-domain-if-available-7MI52MFD.js +7 -0
  155. package/dist/chunks/push-BCSGQBAM.js +7 -0
  156. package/dist/chunks/query-U72BDMAK.js +7 -0
  157. package/dist/chunks/raw-query-4UAW7M5Q.js +8 -0
  158. package/dist/chunks/reauthenticate-HGOLSK2M.js +7 -0
  159. package/dist/chunks/remove-IEEZGRB2.js +9 -0
  160. package/dist/chunks/reorder-YL6L6IWC.js +10 -0
  161. package/dist/chunks/reply-7Y5TN5UV.js +9 -0
  162. package/dist/chunks/resolve-C62436YM.js +12 -0
  163. package/dist/chunks/resolve-agent-team-SR3ALPCH.js +7 -0
  164. package/dist/chunks/restore-Z63JM5CN.js +16 -0
  165. package/dist/chunks/rm-C6QSHEA2.js +8 -0
  166. package/dist/chunks/rm-DDKE62T7.js +8 -0
  167. package/dist/chunks/rm-IUB55CCM.js +8 -0
  168. package/dist/chunks/rm-NZX43GMQ.js +8 -0
  169. package/dist/chunks/rm-UBUI7JNY.js +8 -0
  170. package/dist/chunks/rule-inspect-KF4BLH4K.js +8 -0
  171. package/dist/chunks/{schema-R5JG4UPM.js → schema-L5VCG6FJ.js} +1 -1
  172. package/dist/chunks/schema-P7DFLXCG.js +14 -0
  173. package/dist/chunks/select-org-MBBMOUK2.js +7 -0
  174. package/dist/chunks/set-6U4QIX7A.js +8 -0
  175. package/dist/chunks/set-SCKMJ7LZ.js +7 -0
  176. package/dist/chunks/setup-and-link-5TPDTJIN.js +7 -0
  177. package/dist/chunks/{skills-OA43DLRD.js → skills-ZMFZGPQL.js} +1 -1
  178. package/dist/chunks/tags-7M2EW6LU.js +7 -0
  179. package/dist/chunks/{types-CHIVX5JL.js → types-CVLZCTL2.js} +1 -1
  180. package/dist/chunks/{update-72MKFJ43.js → update-A727QN7H.js} +1 -1
  181. package/dist/chunks/usage-AL4CA45F.js +13 -0
  182. package/dist/chunks/{validate-config-DODT2AQL.js → validate-config-Q77XESW5.js} +1 -1
  183. package/dist/chunks/vercel-cli-3UQLDU2S.js +29 -0
  184. package/dist/commands/build/index.js +1 -1
  185. package/dist/commands/deploy/index.js +4 -4
  186. package/dist/commands/dev/index.js +4 -4
  187. package/dist/commands/env/index.js +12 -12
  188. package/dist/commands/link/index.js +1 -1
  189. package/dist/commands/list/index.js +1 -1
  190. package/dist/commands/project/index.js +14 -9
  191. package/dist/commands/tunnel/index.js +1 -1
  192. package/dist/commands-account.js +6 -6
  193. package/dist/commands-ai.js +18 -10
  194. package/dist/commands-blob.js +1 -1
  195. package/dist/commands-core.js +10 -10
  196. package/dist/commands-deployments.js +1 -1
  197. package/dist/commands-flags.js +1 -1
  198. package/dist/commands-integrations.js +1 -1
  199. package/dist/commands-observability.js +2 -2
  200. package/dist/commands-routing.js +4 -4
  201. package/dist/index.js +6 -6
  202. package/dist/internal-build.js +3 -3
  203. package/dist/package.json +3 -3
  204. package/dist/vc.js +22 -1
  205. package/dist/version.mjs +1 -1
  206. package/package.json +12 -12
  207. package/dist/chunks/add-5NWELDHY.js +0 -8
  208. package/dist/chunks/add-SIXKFK7V.js +0 -8
  209. package/dist/chunks/add-Y5EDLFGD.js +0 -8
  210. package/dist/chunks/alerts-Q2GDU27W.js +0 -8
  211. package/dist/chunks/build-CYUKYXMV.js +0 -7
  212. package/dist/chunks/chunk-2VBFQZ72.js +0 -7
  213. package/dist/chunks/chunk-4NV7UPZE.js +0 -7
  214. package/dist/chunks/chunk-6GKP6VUF.js +0 -7
  215. package/dist/chunks/chunk-6VFNKB5V.js +0 -24
  216. package/dist/chunks/chunk-DTUEHPME.js +0 -7
  217. package/dist/chunks/chunk-HSGWG46B.js +0 -7
  218. package/dist/chunks/chunk-M2GHHK7B.js +0 -11
  219. package/dist/chunks/chunk-PIPRXGDM.js +0 -8
  220. package/dist/chunks/chunk-QK5HTPNC.js +0 -10
  221. package/dist/chunks/chunk-QOLGACFD.js +0 -7
  222. package/dist/chunks/chunk-SNKYDS4V.js +0 -7
  223. package/dist/chunks/chunk-YFMEZ4SZ.js +0 -7
  224. package/dist/chunks/clear-5PKM3HQU.js +0 -8
  225. package/dist/chunks/config-6GAZ64VS.js +0 -7
  226. package/dist/chunks/config-Y77DO6JM.js +0 -8
  227. package/dist/chunks/delete-S5WYOZG7.js +0 -10
  228. package/dist/chunks/delete-WWNN35PK.js +0 -9
  229. package/dist/chunks/disable-LSU7JSDS.js +0 -7
  230. package/dist/chunks/discard-DN4GAN6A.js +0 -14
  231. package/dist/chunks/edit-NUFYISN6.js +0 -9
  232. package/dist/chunks/edit-WQCT2BTX.js +0 -8
  233. package/dist/chunks/enable-ILXOI3I6.js +0 -7
  234. package/dist/chunks/future-5BCEXRHZ.js +0 -7
  235. package/dist/chunks/generate-cert-for-deploy-SXTI35ZG.js +0 -7
  236. package/dist/chunks/image-6OR56EZV.js +0 -7
  237. package/dist/chunks/inspect-OWDUGXCY.js +0 -8
  238. package/dist/chunks/inspect-RU7PVRWQ.js +0 -9
  239. package/dist/chunks/inspect-WJ2A2UKB.js +0 -13
  240. package/dist/chunks/list-CYVRTOUA.js +0 -12
  241. package/dist/chunks/list-JODDYSVR.js +0 -8
  242. package/dist/chunks/login-4L35OD6Y.js +0 -9
  243. package/dist/chunks/login-W5AW34VX.js +0 -7
  244. package/dist/chunks/logs-M3LRI4WS.js +0 -7
  245. package/dist/chunks/ls-QUC3XJDN.js +0 -11
  246. package/dist/chunks/ls-UY36HOHA.js +0 -8
  247. package/dist/chunks/mutate-ETSJAFK6.js +0 -9
  248. package/dist/chunks/notifications-XFMP6MBZ.js +0 -7
  249. package/dist/chunks/open-EOOHIAZV.js +0 -7
  250. package/dist/chunks/openapi-H4PBISI7.js +0 -7
  251. package/dist/chunks/permissions-KOZS3LUK.js +0 -7
  252. package/dist/chunks/prompt-missing-credentials-IV5LGNNZ.js +0 -7
  253. package/dist/chunks/publish-E55JDFF7.js +0 -15
  254. package/dist/chunks/pull-TUTGA5JK.js +0 -7
  255. package/dist/chunks/purchase-domain-if-available-6SARYPIK.js +0 -7
  256. package/dist/chunks/push-UBTJMO6Q.js +0 -7
  257. package/dist/chunks/query-KTJNUSFP.js +0 -7
  258. package/dist/chunks/raw-query-D3KKMGEJ.js +0 -8
  259. package/dist/chunks/reauthenticate-HYQL6JW7.js +0 -7
  260. package/dist/chunks/remove-QERLIR4R.js +0 -9
  261. package/dist/chunks/reorder-UCGI2FFJ.js +0 -10
  262. package/dist/chunks/reply-FRHAEVBD.js +0 -9
  263. package/dist/chunks/resolve-Z33ONVMR.js +0 -12
  264. package/dist/chunks/resolve-agent-team-ER4RZEJT.js +0 -7
  265. package/dist/chunks/restore-LQFGPBOB.js +0 -16
  266. package/dist/chunks/rm-4Z5TWVJJ.js +0 -8
  267. package/dist/chunks/rm-AOOIB5ZS.js +0 -8
  268. package/dist/chunks/rm-HCFBMSNJ.js +0 -8
  269. package/dist/chunks/rm-PAHHUTML.js +0 -8
  270. package/dist/chunks/rm-QVKGQ4UB.js +0 -8
  271. package/dist/chunks/rule-inspect-5VM4YF7A.js +0 -8
  272. package/dist/chunks/schema-MUBIHAGZ.js +0 -14
  273. package/dist/chunks/select-org-SGALVKOW.js +0 -7
  274. package/dist/chunks/set-NFLZFD7O.js +0 -7
  275. package/dist/chunks/set-SVOTRX7Z.js +0 -8
  276. package/dist/chunks/setup-and-link-7SPTSXXZ.js +0 -7
  277. package/dist/chunks/tags-BIX4YRL3.js +0 -7
  278. package/dist/chunks/usage-24PRDBPS.js +0 -13
@@ -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{sleep}from"./chunk-IBZJP22D.js";import{fetch}from"./chunk-MY4MONOH.js";import{getCommandNamePlain}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);var BYPASS_READY_DELAYS_MS=[250,500,1e3,2e3,2e3,2e3,2e3,2e3],BYPASS_READY_TIMEOUT_MS=12e3,BYPASS_READY_REQUEST_TIMEOUT_MS=3e3,PROTECTION_BODY_MAX_BYTES=16*1024;async function createDeploymentProtectionToken(client,projectId,orgId){if(!client.authConfig.token)throw output_manager_default.debug("No auth token available, skipping deployment protection token"),new Error("Authentication required to create protection bypass token");try{let response=await client.fetch(`/v1/projects/${projectId}/protection-bypass`,{method:"PATCH",body:"{}",headers:{"Content-Type":"application/json"},accountId:orgId}),{protectionBypass}=response,token=getAutomationBypassToken(protectionBypass);return output_manager_default.log(`Added a Protection Bypass for Automation secret to project ${import_chalk.default.bold(projectId)}. It stays on the project until you revoke it.`),output_manager_default.print(` To revoke it, open Deployment Protection in the project settings, or run:
7
+ import{sleep}from"./chunk-Z2KANBOU.js";import{fetch}from"./chunk-MY4MONOH.js";import{getCommandNamePlain}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);var BYPASS_READY_DELAYS_MS=[250,500,1e3,2e3,2e3,2e3,2e3,2e3],BYPASS_READY_TIMEOUT_MS=12e3,BYPASS_READY_REQUEST_TIMEOUT_MS=3e3,PROTECTION_BODY_MAX_BYTES=16*1024;async function createDeploymentProtectionToken(client,projectId,orgId){if(!client.authConfig.token)throw output_manager_default.debug("No auth token available, skipping deployment protection token"),new Error("Authentication required to create protection bypass token");try{let response=await client.fetch(`/v1/projects/${projectId}/protection-bypass`,{method:"PATCH",body:"{}",headers:{"Content-Type":"application/json"},accountId:orgId}),{protectionBypass}=response,token=getAutomationBypassToken(protectionBypass);return output_manager_default.log(`Added a Protection Bypass for Automation secret to project ${import_chalk.default.bold(projectId)}. It stays on the project until you revoke it.`),output_manager_default.print(` To revoke it, open Deployment Protection in the project settings, or run:
8
8
  ${getCommandNamePlain(`project protection disable ${projectId} --protection-bypass --protection-bypass-secret <secret>`)}
9
9
 
10
10
  `),token}catch(error){throw output_manager_default.debug(`Failed to generate deployment protection bypass token: ${error}`),output_manager_default.note('To bypass deployment protection, create a "Protection Bypass for Automation" secret in your project settings:'),output_manager_default.log(` 1. Visit ${import_chalk.default.cyan("https://vercel.com/dashboard")}`),output_manager_default.log(" 2. Go to your project settings \u2192 Deployment Protection"),output_manager_default.log(' 3. Generate a "Protection Bypass for Automation" secret'),output_manager_default.log(` 4. Use it with ${import_chalk.default.cyan("--protection-bypass")} option or set ${import_chalk.default.cyan("VERCEL_AUTOMATION_BYPASS_SECRET")} env var`),output_manager_default.log(""),new Error("Failed to create deployment protection bypass token")}}function getAutomationBypassToken(protectionBypass){if(!protectionBypass)throw new Error("No protection bypass tokens found");let token=Object.keys(protectionBypass).find(key=>protectionBypass[key].scope==="automation-bypass");if(!token)throw new Error("No automation bypass token found in protection bypass settings");return token}async function getOrCreateDeploymentProtectionToken(client,{project,org},{createIfMissing=!0,readinessUrl}={}){if(process.env.VERCEL_AUTOMATION_BYPASS_SECRET)return output_manager_default.debug("Using protection bypass secret from environment variable"),process.env.VERCEL_AUTOMATION_BYPASS_SECRET;if(project.protectionBypass&&Object.values(project.protectionBypass).length){let protectionBypass;try{protectionBypass=getAutomationBypassToken(project.protectionBypass)}catch(error){if(!createIfMissing)return output_manager_default.debug(`No existing automation bypass token found for project ${project.id}`),null;throw error}if(protectionBypass)return output_manager_default.debug("Using existing protection bypass token from project settings"),protectionBypass}if(!createIfMissing)return output_manager_default.debug(`Not creating an automation bypass token for project ${project.id}`),null;let token=await createDeploymentProtectionToken(client,project.id,org.id);return readinessUrl?(await waitForProtectionBypass(readinessUrl,token)||output_manager_default.warning("The new bypass secret is not active yet, so this request can return the Deployment Protection page. If it does, run the command again in a few seconds."),token):(await sleep(1e3),token)}async function waitForProtectionBypass(url,token){let origin=new URL(url).origin,deadline=Date.now()+BYPASS_READY_TIMEOUT_MS;output_manager_default.spinner("Waiting for the new bypass secret to become active\u2026");try{for(let attempt=0;;attempt++){let remaining=deadline-Date.now(),protectedResponse;try{protectedResponse=await isProtected(origin,token,Math.max(1,Math.min(BYPASS_READY_REQUEST_TIMEOUT_MS,remaining)))}catch(err){return output_manager_default.debug(`Could not check the new bypass secret: ${err}`),!0}if(!protectedResponse)return output_manager_default.debug(`The new bypass secret works after ${attempt+1} checks`),!0;let delay=BYPASS_READY_DELAYS_MS[attempt];if(delay===void 0||Date.now()+delay>=deadline)return output_manager_default.debug(`The new bypass secret did not work after ${attempt+1} checks`),!1;await sleep(delay)}}finally{output_manager_default.stopSpinner()}}async function isProtected(origin,token,timeoutMs){let res=await fetch(`${origin}/`,{headers:{accept:"application/json","x-vercel-protection-bypass":token},redirect:"manual",signal:AbortSignal.timeout(timeoutMs)});try{return await isProtectionResponse(res,origin)}finally{await res.body?.cancel().catch(()=>{})}}async function isProtectionResponse(res,origin){let location=res.headers.get("location");if(res.status>=300&&res.status<400&&location){let target=new URL(location,origin);return target.host==="vercel.com"&&target.pathname==="/sso-api"}let contentType=res.headers.get("content-type")??"";if(res.status!==401||!contentType.includes("application/json"))return!1;try{let text=await readBodyUpTo(res,PROTECTION_BODY_MAX_BYTES);return text===null?!1:JSON.parse(text)?.error?.message==="Protected deployment"}catch{return!1}}async function readBodyUpTo(res,maxBytes){let reader=res.body?.getReader();if(!reader)return"";let chunks=[],size=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(size+=value.byteLength,size>maxBytes)return await reader.cancel(),null;chunks.push(value)}}finally{reader.releaseLock()}return Buffer.concat(chunks).toString("utf8")}export{getOrCreateDeploymentProtectionToken};
@@ -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{collectContactInformation,getDomainPrice,getDomainStatus,purchaseDomain}from"./chunk-O42P2UDX.js";import{stamp_default}from"./chunk-A2RZZQEP.js";import{param}from"./chunk-3G3FQYMW.js";import{buildCommandWithGlobalFlags}from"./chunk-M2GHHK7B.js";import{require_pluralize}from"./chunk-4HR3I3ML.js";import{DomainNotAvailable,DomainNotFound,DomainOrderPending,UnsupportedTLD,UserAborted}from"./chunk-GOI2VVI7.js";import{eraseLines,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),import_pluralize=__toESM(require_pluralize(),1);var isTTY=process.stdout.isTTY;async function purchaseDomainIfAvailable(client,domain,contextName){output_manager_default.spinner(`Checking status of ${import_chalk.default.bold(domain)}`);let buyDomainStamp=stamp_default(),{available}=await getDomainStatus(client,domain);if(available){if(!isTTY)return new DomainNotFound(domain);output_manager_default.debug(`Domain ${domain} is available to be purchased`);let domainPrice=await getDomainPrice(client,domain).finally(()=>{output_manager_default.stopSpinner()});if(domainPrice instanceof UnsupportedTLD)return domainPrice;if(domainPrice instanceof Error)throw domainPrice;let{purchasePrice,years}=domainPrice;if(purchasePrice===null)return output_manager_default.error(`The domain ${param(domain)} is ${import_chalk.default.underline("unavailable")}! ${buyDomainStamp()}`),new DomainNotAvailable(domain);if(output_manager_default.log(`Domain not found, but you can buy it under ${import_chalk.default.bold(contextName)}! ${buyDomainStamp()}`),!await client.input.confirm(`Buy ${import_chalk.default.underline(domain)} for ${import_chalk.default.bold(`$${purchasePrice}`)} (${(0,import_pluralize.default)("yr",years,!0)})?`,!1))return output_manager_default.print(eraseLines(1)),new UserAborted;output_manager_default.print(eraseLines(1));let contactInformation=await collectContactInformation(client);output_manager_default.spinner("Purchasing");let result=await purchaseDomain(client,domain,purchasePrice,years,!0,contactInformation,{onOrderAccepted:orderId=>{output_manager_default.stopSpinner(),output_manager_default.log(`Order ${orderId} accepted.`),output_manager_default.spinner(`Waiting on the registrar to register ${domain}`)}}).finally(()=>output_manager_default.stopSpinner());return result instanceof Error?result:result.status==="pending"?new DomainOrderPending(domain,result.orderId,buildCommandWithGlobalFlags(client.argv,`api /v1/registrar/orders/${result.orderId}`)):result.status==="already_owned"?result:!0}return output_manager_default.debug(`Domain ${domain} is not available to be purchased`),!1}export{purchaseDomainIfAvailable};
7
+ import{collectContactInformation,getDomainPrice,getDomainStatus,purchaseDomain}from"./chunk-BCAI7MED.js";import{stamp_default}from"./chunk-A2RZZQEP.js";import{param}from"./chunk-3G3FQYMW.js";import{require_pluralize}from"./chunk-4HR3I3ML.js";import{buildCommandWithGlobalFlags}from"./chunk-4SS6W6JK.js";import{DomainNotAvailable,DomainNotFound,DomainOrderPending,UnsupportedTLD,UserAborted}from"./chunk-GOI2VVI7.js";import{eraseLines,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),import_pluralize=__toESM(require_pluralize(),1);var isTTY=process.stdout.isTTY;async function purchaseDomainIfAvailable(client,domain,contextName){output_manager_default.spinner(`Checking status of ${import_chalk.default.bold(domain)}`);let buyDomainStamp=stamp_default(),{available}=await getDomainStatus(client,domain);if(available){if(!isTTY)return new DomainNotFound(domain);output_manager_default.debug(`Domain ${domain} is available to be purchased`);let domainPrice=await getDomainPrice(client,domain).finally(()=>{output_manager_default.stopSpinner()});if(domainPrice instanceof UnsupportedTLD)return domainPrice;if(domainPrice instanceof Error)throw domainPrice;let{purchasePrice,years}=domainPrice;if(purchasePrice===null)return output_manager_default.error(`The domain ${param(domain)} is ${import_chalk.default.underline("unavailable")}! ${buyDomainStamp()}`),new DomainNotAvailable(domain);if(output_manager_default.log(`Domain not found, but you can buy it under ${import_chalk.default.bold(contextName)}! ${buyDomainStamp()}`),!await client.input.confirm(`Buy ${import_chalk.default.underline(domain)} for ${import_chalk.default.bold(`$${purchasePrice}`)} (${(0,import_pluralize.default)("yr",years,!0)})?`,!1))return output_manager_default.print(eraseLines(1)),new UserAborted;output_manager_default.print(eraseLines(1));let contactInformation=await collectContactInformation(client);output_manager_default.spinner("Purchasing");let result=await purchaseDomain(client,domain,purchasePrice,years,!0,contactInformation,{onOrderAccepted:orderId=>{output_manager_default.stopSpinner(),output_manager_default.log(`Order ${orderId} accepted.`),output_manager_default.spinner(`Waiting on the registrar to register ${domain}`)}}).finally(()=>output_manager_default.stopSpinner());return result instanceof Error?result:result.status==="pending"?new DomainOrderPending(domain,result.orderId,buildCommandWithGlobalFlags(client.argv,`api /v1/registrar/orders/${result.orderId}`)):result.status==="already_owned"?result:!0}return output_manager_default.debug(`Domain ${domain} is not available to be purchased`),!1}export{purchaseDomainIfAvailable};
@@ -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{require_dist as require_dist2}from"./chunk-AMOI3EAW.js";import{require_dist}from"./chunk-ISSNEDG5.js";import{require_types}from"./chunk-AW33SRYY.js";import{require_build_utils}from"./chunk-5MDNVAE6.js";import{__commonJS,__require,__toESM}from"./chunk-BZENIQ7N.js";var require_constants=__commonJS({"../runtimes/dist/constants.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),constants_exports={};__export(constants_exports,{BUILDER_RUNTIMES:()=>BUILDER_RUNTIMES,CONTAINER_ENTRYPOINT_CANDIDATES:()=>CONTAINER_ENTRYPOINT_CANDIDATES,ENTRYPOINT_EXTENSIONS:()=>ENTRYPOINT_EXTENSIONS,ROUTE_OWNING_BUILDERS:()=>ROUTE_OWNING_BUILDERS,RUNTIME_BUILDERS:()=>RUNTIME_BUILDERS,RUNTIME_MANIFESTS:()=>RUNTIME_MANIFESTS,STATIC_BUILDERS:()=>STATIC_BUILDERS});module.exports=__toCommonJS(constants_exports);var RUNTIME_BUILDERS={node:"@vercel/backends",python:"@vercel/python",go:"@vercel/go",rust:"@vercel/rust",ruby:"@vercel/ruby",container:"@vercel/container"},RUNTIME_MANIFESTS={node:["package.json"],python:["pyproject.toml","requirements.txt","Pipfile","pylock.yml","uv.lock","setup.py"],go:["go.mod"],ruby:["Gemfile"],rust:["Cargo.toml"]},ENTRYPOINT_EXTENSIONS={".ts":"node",".mts":"node",".js":"node",".mjs":"node",".cjs":"node",".py":"python",".go":"go",".rs":"rust",".rb":"ruby",".ru":"ruby"},BUILDER_RUNTIMES={...Object.fromEntries(Object.entries(RUNTIME_BUILDERS).map(([runtime,builder])=>[builder,runtime])),"@vercel/node":"node","@vercel/next":"node","@vercel/remix-builder":"node","@vercel/redwood":"node","@vercel/hydrogen":"node","@vercel/express":"node","@vercel/hono":"node","@vercel/h3":"node","@vercel/koa":"node","@vercel/nestjs":"node","@vercel/fastify":"node","@vercel/elysia":"node"},STATIC_BUILDERS=new Set(["@vercel/static-build","@vercel/static"]),ROUTE_OWNING_BUILDERS=new Set(["@vercel/next","@vercel/backends"]),CONTAINER_ENTRYPOINT_CANDIDATES=["Dockerfile.vercel","Containerfile.vercel","Dockerfile","Containerfile"]}});var require_entrypoint=__commonJS({"../runtimes/dist/entrypoint.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),entrypoint_exports={};__export(entrypoint_exports,{isDockerfileEntrypoint:()=>isDockerfileEntrypoint,isNodeScheduleEntrypoint:()=>isNodeScheduleEntrypoint2,parsePyModuleAttrEntrypoint:()=>parsePyModuleAttrEntrypoint,parsePythonScheduleModule:()=>parsePythonScheduleModule2,stripTrailingSlash:()=>stripTrailingSlash});module.exports=__toCommonJS(entrypoint_exports);var import_path=__require("path"),import_constants=require_constants(),PYTHON_MODULE_ATTR_RE=/^([A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*):([A-Za-z_][\w]*)$/,PYTHON_MODULE_RE=/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/,SOURCE_FILE_RE=/\.(?:py|[cm]?[jt]s)$/,NODE_SOURCE_FILE_RE=/\.(?:m?js|[cm]?ts)$/;function parsePyModuleAttrEntrypoint(entrypoint){let match=PYTHON_MODULE_ATTR_RE.exec(entrypoint);if(!match)return null;let[,modulePart,attrName]=match;return!modulePart||!attrName?null:{attrName,filePath:modulePart.replace(/\./g,"/")+".py",moduleName:modulePart}}function parsePythonScheduleModule2(entrypoint){if(!PYTHON_MODULE_RE.test(entrypoint)||SOURCE_FILE_RE.test(entrypoint))return null;let path=entrypoint.replace(/\./g,"/");return{moduleName:entrypoint,sourceFiles:[`${path}/__init__.py`,`${path}.py`]}}function isNodeScheduleEntrypoint2(entrypoint){return NODE_SOURCE_FILE_RE.test(entrypoint)}var CONTAINER_ENTRYPOINT_BASENAMES=new Set(import_constants.CONTAINER_ENTRYPOINT_CANDIDATES.map(name=>name.toLowerCase()));function isDockerfileEntrypoint(entrypoint){return CONTAINER_ENTRYPOINT_BASENAMES.has(import_path.posix.basename(entrypoint).toLowerCase())}function stripTrailingSlash(p){let stripped=p.replace(/\/+$/,"");return stripped===""?".":stripped}}});var import_routing_utils=__toESM(require_dist(),1),import_build_utils=__toESM(require_build_utils(),1),import_types=__toESM(require_types(),1),import_fs_detectors=__toESM(require_dist2(),1),import_entrypoint=__toESM(require_entrypoint(),1);import{getConfigValidator}from"./config-validator.mjs";var imagesSchema={type:"object",additionalProperties:!1,required:["sizes"],properties:{contentDispositionType:{enum:["inline","attachment"]},contentSecurityPolicy:{type:"string",minLength:1,maxLength:256},dangerouslyAllowSVG:{type:"boolean"},domains:{type:"array",minItems:0,maxItems:50,items:{type:"string",minLength:1,maxLength:256}},formats:{type:"array",minItems:1,maxItems:4,items:{enum:["image/avif","image/webp","image/jpeg","image/png"]}},localPatterns:{type:"array",minItems:0,maxItems:25,items:{type:"object",additionalProperties:!1,properties:{pathname:{type:"string",minLength:1,maxLength:256},search:{type:"string",minLength:0,maxLength:256}}}},minimumCacheTTL:{type:"integer",minimum:1,maximum:31536e4},qualities:{type:"array",minItems:1,maxItems:20,items:{type:"integer",minimum:1,maximum:100}},remotePatterns:{type:"array",minItems:0,maxItems:50,items:{type:"object",additionalProperties:!1,required:["hostname"],properties:{protocol:{enum:["http","https"]},hostname:{type:"string",minLength:1,maxLength:256},port:{type:"string",minLength:0,maxLength:5},pathname:{type:"string",minLength:1,maxLength:256},search:{type:"string",minLength:0,maxLength:256}}}},sizes:{type:"array",minItems:1,maxItems:50,items:{type:"number"}}}},cronsSchema={type:"array",minItems:0,items:{type:"object",additionalProperties:!1,required:["path","schedule"],properties:{path:{type:"string",minLength:1,maxLength:512,pattern:"^/.*"},schedule:{type:"string",minLength:9,maxLength:256}}}},scheduleNameSchema={type:"string",minLength:1,maxLength:256,pattern:"^[0-9A-Za-z][0-9A-Za-z._-]*$"},scheduleDefinitionSchema={type:"object",additionalProperties:!1,properties:{schedule:{type:"string",minLength:9,maxLength:256},timezone:{type:"string",minLength:1,maxLength:50,description:"IANA timezone for cron evaluation. Defaults to UTC."},jitter:{type:"integer",minimum:1,maximum:15},path:{description:"Deployment path to invoke over HTTP, like `crons[].path`. Must start with `/`.",type:"string",maxLength:512,pattern:"^/"},requestMethod:{description:"HTTP method used to invoke `path`. Only valid with `path`. Defaults to `POST`.",enum:["GET","POST"]},function:{type:"string",minLength:1},service:{description:"Service that owns `function`, from `services`. When set, `function` is the path within that service. Only valid with `function`.",type:"string",minLength:1,maxLength:64,pattern:"^[a-z]([a-z_-]*[a-z])?$"},topic:{type:"string",minLength:1,maxLength:256,pattern:"^[A-Za-z0-9_-]+$"},run:{description:"Command to run for each firing. Only valid with a Dockerfile or Containerfile entrypoint.",type:"array",minItems:1,items:[{type:"string",pattern:"\\S"}],additionalItems:{type:"string"}},root:{description:"Directory of the service that runs the schedule's `entrypoint`, which is relative to it. Required with `entrypoint`.",type:"string",minLength:1,maxLength:512},entrypoint:{type:"string",minLength:1,maxLength:512},runtime:{description:"Runtime of an `entrypoint` without `run`: `python` for a module path like `jobs.tasks`, or `node` for a JavaScript or TypeScript file.",enum:["python","node"]}},dependencies:{requestMethod:["path"],service:["function"],run:["entrypoint"],entrypoint:["root"],root:["entrypoint"]},oneOf:[{required:["path"]},{required:["function"]},{required:["topic"]},{required:["entrypoint"]}]},maxSchedules=500,schedulesSchema={type:"object",maxProperties:maxSchedules,propertyNames:scheduleNameSchema,additionalProperties:scheduleDefinitionSchema},experimentalServicesMountSchema={oneOf:[{type:"string",minLength:1,maxLength:512},{type:"object",additionalProperties:!1,properties:{path:{type:"string",minLength:1,maxLength:512},subdomain:{type:"string",minLength:1,maxLength:63}},anyOf:[{required:["path"]},{required:["subdomain"]}]}]},staticExperimentalServiceScheduleSchema={type:"string",minLength:9,maxLength:256,not:{const:"<dynamic>"}},experimentalServiceScheduleSchema={oneOf:[{type:"string",minLength:9,maxLength:256},{type:"array",minItems:1,items:staticExperimentalServiceScheduleSchema}]},experimentalServiceQueueTopicSchema={type:"object",additionalProperties:!1,required:["topic"],properties:{topic:{type:"string",minLength:1,maxLength:256},retryAfterSeconds:{type:"integer",minimum:1,maximum:86400},initialDelaySeconds:{type:"integer",minimum:0,maximum:86400}}},experimentalServiceTopicsSchema={oneOf:[{type:"array",minItems:1,items:{type:"string",minLength:1,maxLength:256}},{type:"array",minItems:1,items:experimentalServiceQueueTopicSchema}]},envVarNamesSchema={pattern:"^[A-Za-z_][A-Za-z0-9_]*$",maxLength:256},getExperimentalServicesCommonProperties=()=>({entrypoint:{type:"string",minLength:1,maxLength:512},root:{type:"string",minLength:1,maxLength:512},workspace:{type:"string",minLength:1,maxLength:512},framework:{type:"string",minLength:1,maxLength:256},builder:{type:"string",minLength:1,maxLength:256},runtime:{type:"string",minLength:1,maxLength:256},buildCommand:{type:"string",minLength:1,maxLength:2048},installCommand:{type:"string",minLength:1,maxLength:2048},preDeployCommand:{type:"string",minLength:1,maxLength:2048},command:{oneOf:[{type:"string",minLength:1,maxLength:2048},{type:"array",minItems:1,items:{type:"string",minLength:1,maxLength:2048}}]},memory:{type:"integer",minimum:128,maximum:10240},maxDuration:(0,import_build_utils.getMaxDurationSchema)(),includeFiles:{oneOf:[{type:"string",minLength:1},{type:"array",items:{type:"string",minLength:1}}]},excludeFiles:{oneOf:[{type:"string",minLength:1},{type:"array",items:{type:"string",minLength:1}}]}}),experimentalServicesRoutableProperties={mount:experimentalServicesMountSchema,routePrefix:{type:"string",minLength:1,maxLength:512},subdomain:{type:"string",minLength:1,maxLength:63}},getExperimentalServicesServiceConfigSchema=()=>({oneOf:[{type:"object",additionalProperties:!1,properties:{...getExperimentalServicesCommonProperties(),...experimentalServicesRoutableProperties,type:{enum:["web"]}}},{type:"object",additionalProperties:!1,required:["type","trigger","schedule"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"job"},trigger:{const:"schedule"},schedule:experimentalServiceScheduleSchema}},{type:"object",additionalProperties:!1,required:["type","trigger","topics"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"job"},trigger:{const:"queue"},topics:experimentalServiceTopicsSchema,consumer:{type:"string",minLength:1,maxLength:256}}},{type:"object",additionalProperties:!1,required:["type","trigger","entrypoint"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"job"},trigger:{const:"workflow"}}},{type:"object",additionalProperties:!1,required:["type"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"worker"},topics:{type:"array",items:{type:"string",minLength:1,maxLength:256},minItems:1},consumer:{type:"string",minLength:1,maxLength:256}}},{type:"object",additionalProperties:!1,required:["type","schedule"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"cron"},schedule:experimentalServiceScheduleSchema}}]}),getExperimentalServicesSchema=()=>({type:"object",propertyNames:{pattern:"^[a-zA-Z]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$",maxLength:64},additionalProperties:getExperimentalServicesServiceConfigSchema()}),experimentalServiceGroupsSchema={type:"object",propertyNames:{pattern:"^[a-zA-Z]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$",maxLength:64},additionalProperties:{type:"array",items:{type:"string",minLength:1,maxLength:256}}},servicesPathSchema={type:"string",minLength:1,maxLength:512},servicesCommandSchema={type:"string",minLength:1,maxLength:2048},servicesBindingSchema={type:"object",additionalProperties:!1,required:["service","format","env"],properties:{type:{description:"Optional binding type marker. Currently the only supported type is `service`. When present this must be `service`.",const:"service"},service:{type:"string",minLength:1,maxLength:64,pattern:import_build_utils.SERVICE_NAME_PATTERN},format:{const:"url"},env:{type:"string",...envVarNamesSchema}}},servicesBindingsSchema={type:"array",maxItems:100,items:servicesBindingSchema},getServicesServiceConfigSchema=()=>({type:"object",additionalProperties:!1,required:["root"],properties:{root:servicesPathSchema,framework:{type:"string",minLength:1,maxLength:256},runtime:{type:"string",minLength:1,maxLength:256},entrypoint:servicesPathSchema,command:{oneOf:[{type:"string",minLength:1,maxLength:4096},{type:"array",minItems:1,maxItems:128,items:{type:"string",minLength:1,maxLength:4096}}]},installCommand:servicesCommandSchema,buildCommand:servicesCommandSchema,devCommand:servicesCommandSchema,ignoreCommand:servicesCommandSchema,outputDirectory:servicesPathSchema,bindings:servicesBindingsSchema,functions:(0,import_build_utils.getFunctionsSchema)(),headers:import_routing_utils.headersSchema,redirects:import_routing_utils.redirectsSchema,rewrites:import_routing_utils.rewritesSchema,routes:import_routing_utils.routesSchema,cleanUrls:import_routing_utils.cleanUrlsSchema,trailingSlash:import_routing_utils.trailingSlashSchema}}),daemonConfigSchema={type:"object",additionalProperties:!1,required:["root","entrypoint"],anyOf:[{required:["instances"]},{required:["replicas"]}],properties:{root:servicesPathSchema,entrypoint:servicesPathSchema,command:{type:"array",minItems:1,maxItems:128,items:{type:"string",minLength:1,maxLength:4096}},instances:{type:"object",additionalProperties:{type:"integer",minimum:0}},replicas:{description:"Deprecated. Use `instances`. Ignored when `instances` is set.",deprecated:!0,type:"object",additionalProperties:{type:"integer",minimum:0}},resources:{type:"object",additionalProperties:!1,required:["requests"],properties:{requests:{type:"object",additionalProperties:!1,required:["memory"],properties:{memory:{enum:["1Gi","2Gi","4Gi","8Gi"]}}}}},terminationGracePeriodSeconds:{type:"integer",minimum:0},livenessProbe:{type:"object",additionalProperties:!1,required:["httpGet"],properties:{httpGet:{type:"object",additionalProperties:!1,required:["port"],properties:{path:{type:"string",minLength:1},port:{type:"integer",minimum:1,maximum:65535},host:{type:"string",minLength:1},scheme:{enum:["HTTP","HTTPS"]},httpHeaders:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","value"],properties:{name:{type:"string",minLength:1},value:{type:"string"}}}}}},initialDelaySeconds:{type:"integer",minimum:0,maximum:86400},periodSeconds:{type:"integer",minimum:1,maximum:86400},timeoutSeconds:{type:"integer",minimum:1,maximum:86400},successThreshold:{type:"integer",minimum:1,maximum:10},failureThreshold:{type:"integer",minimum:1,maximum:10}}},bindings:{...servicesBindingsSchema,items:{...servicesBindingSchema,required:["type",...servicesBindingSchema.required]}}}},getServicesSchema=()=>({type:"object",propertyNames:{pattern:import_build_utils.SERVICE_NAME_PATTERN,maxLength:64},additionalProperties:getServicesServiceConfigSchema()}),maxDaemons=100,daemonsSchema={type:"object",maxProperties:maxDaemons,propertyNames:{pattern:import_build_utils.DAEMON_NAME_PATTERN,maxLength:64},additionalProperties:daemonConfigSchema},proxySchema={type:"object",additionalProperties:!1,required:["entrypoint"],properties:{entrypoint:{type:"string",minLength:1},matcher:{oneOf:[{type:"string",minLength:1},{type:"array",minItems:1,items:{type:"string",minLength:1}}]}}};function buildVercelConfigSchema(){return{type:"object",additionalProperties:!0,properties:{builds:import_build_utils.buildsSchema,routes:import_routing_utils.routesSchema,cleanUrls:import_routing_utils.cleanUrlsSchema,headers:import_routing_utils.headersSchema,redirects:import_routing_utils.redirectsSchema,rewrites:import_routing_utils.rewritesSchema,trailingSlash:import_routing_utils.trailingSlashSchema,functions:(0,import_build_utils.getFunctionsSchema)(),images:imagesSchema,crons:cronsSchema,schedules:schedulesSchema,bunVersion:{type:"string"},proxy:proxySchema,experimentalServices:getExperimentalServicesSchema(),experimentalServiceGroups:experimentalServiceGroupsSchema,services:getServicesSchema(),experimentalServicesV2:getServicesSchema(),daemons:daemonsSchema}}}var isDockerfilePath=entrypoint=>/(docker|container)file/i.test((0,import_build_utils.splitDockerfileEntrypoint)(entrypoint).path.split(/[\\/]/).pop()??""),toPythonModulePath=entrypoint=>entrypoint.replace(/\.py$/,"").replace(/[\\/]+/g,".").replace(/(^|\.)__init__$/,""),hasInvalidDockerfileStage=entrypoint=>{let{buildTarget}=(0,import_build_utils.splitDockerfileEntrypoint)(entrypoint);return buildTarget!==void 0&&!(0,import_build_utils.isValidDockerfileStage)(buildTarget)};function validateConfig(config){let validate=getConfigValidator(buildVercelConfigSchema);if(!validate(config)&&validate.errors&&validate.errors[0]){let error=validate.errors[0],fileName=config[import_types.fileNameSymbol]||"vercel.json",niceError=(0,import_build_utils.getPrettyError)(error);return niceError.message=`Invalid ${fileName} - ${niceError.message}`,niceError}let serviceNames=new Set([...Object.keys(config.services??{}),...Object.keys(config.daemons??{})]),scheduleServices=getScheduleServiceNames(config),destinationServices=new Set(getDestinationServices(config)),invalidSchedule=(code,message)=>new import_build_utils.NowBuildError({code,message:`Invalid ${config[import_types.fileNameSymbol]||"vercel.json"} - ${message}`}),invalidCommand=message=>invalidSchedule("INVALID_SCHEDULE_COMMAND",message),invalidEntrypoint=message=>invalidSchedule("INVALID_SCHEDULE_ENTRYPOINT",message);for(let[name,schedule]of Object.entries(config.schedules??{})){let path=`schedules.${name}`;if("runtime"in schedule&&("run"in schedule||!("entrypoint"in schedule)))return invalidEntrypoint(`\`${path}.runtime\` is only valid with an \`entrypoint\` and without \`run\`.`);if("entrypoint"in schedule&&!("run"in schedule)){let{entrypoint,runtime}=schedule;if(!runtime)return isDockerfilePath(entrypoint)?invalidEntrypoint(`\`${path}.entrypoint\` names a Dockerfile, so \`${path}\` must set \`run\`.`):invalidEntrypoint(`\`${path}\` must set \`runtime\` to run its \`entrypoint\`: "python" for a module path like "jobs.tasks", or "node" for a .js, .mjs, .ts, .mts or .cts file.`);if(runtime==="python"&&!(0,import_entrypoint.parsePythonScheduleModule)(entrypoint)){let suggestion=entrypoint.endsWith(".py")?toPythonModulePath(entrypoint):"";return invalidEntrypoint(`\`${path}.entrypoint\` "${entrypoint}" must be a Python module path like "${(0,import_entrypoint.parsePythonScheduleModule)(suggestion)?suggestion:"jobs.tasks"}", since \`${path}.runtime\` is "python".`)}if(runtime==="node"&&!(0,import_entrypoint.isNodeScheduleEntrypoint)(entrypoint))return invalidEntrypoint(`\`${path}.entrypoint\` "${entrypoint}" must be a .js, .mjs, .ts, .mts or .cts file, since \`${path}.runtime\` is "node".`);let configured=["schedule","timezone","jitter"].find(key=>key in schedule);if(configured)return invalidEntrypoint(runtime==="node"?`\`${path}\` runs "${entrypoint}", whose \`export const config\` sets its cron, timezone and jitter. Remove \`${path}.${configured}\`.`:`\`${path}\` runs the Python module "${entrypoint}", whose \`@schedule\` handlers set their own cron, timezone and jitter. Remove \`${path}.${configured}\`.`)}else if(!("schedule"in schedule))return invalidSchedule("INVALID_SCHEDULE_EXPRESSION",`\`${path}\` is missing required property \`schedule\`.`);if("run"in schedule){if(!isDockerfilePath(schedule.entrypoint))return invalidCommand(`\`${path}.run\` requires a Dockerfile or Containerfile \`entrypoint\`.`);if(hasInvalidDockerfileStage(schedule.entrypoint))return invalidCommand(`\`${path}.entrypoint\` "${schedule.entrypoint}" is invalid. ${import_build_utils.DOCKERFILE_STAGE_HINT}`)}if(scheduleServices.has(name)){if(name.length>64||!new RegExp(import_build_utils.SERVICE_NAME_PATTERN).test(name))return invalidScheduleService(config,`\`${path}\` runs as a service, so its name must be a valid service name: lowercase letters, \`-\` and \`_\`, at most 64 characters.`);if(serviceNames.has(name))return invalidScheduleService(config,`\`${path}\` runs as service "${name}", which is already the name of a service or daemon.`);if(destinationServices.has(name))return invalidScheduleService(config,`Rewrites and routes cannot target schedule "${name}" because schedules do not receive traffic.`)}if(!(!("timezone"in schedule)||schedule.timezone===void 0))try{if(!/^[A-Za-z][A-Za-z0-9_+/-]*$/.test(schedule.timezone))throw new RangeError("Expected a named timezone");new Intl.DateTimeFormat("en-US",{timeZone:schedule.timezone})}catch{return new import_build_utils.NowBuildError({code:"INVALID_SCHEDULE_TIMEZONE",message:`Invalid ${config[import_types.fileNameSymbol]||"vercel.json"} - \`schedules.${name}.timezone\` must be a valid IANA timezone, such as "America/New_York". Omit it to use UTC.`})}}let functionMaps=[config.functions,...Object.values(config.services??{}).map(service=>service.functions),...Object.values(config.experimentalServicesV2??{}).map(service=>service.functions)];for(let functions of functionMaps)for(let[pattern,fn]of Object.entries(functions??{})){let regions=[...new Set(fn.regions)];if(fn.affinity?.mode==="strict"&&(regions.includes("all")||regions.length>1))return new import_build_utils.NowBuildError({code:"INVALID_FUNCTION_AFFINITY_REGIONS",message:`Function affinity mode "strict" requires at most one statically configured region. Update \`functions[${JSON.stringify(pattern)}].regions\` to contain a single region.`,link:"https://vercel.com/docs/concepts/projects/project-configuration#functions"})}if(config.proxy){let proxyError=(0,import_fs_detectors.validateProxyConfig)(config.proxy);if(proxyError)return new import_build_utils.NowBuildError({code:proxyError.code.toUpperCase(),message:proxyError.message})}if(config.functions&&config.builds)return new import_build_utils.NowBuildError({code:"FUNCTIONS_AND_BUILDS",message:"The `functions` property cannot be used in conjunction with the `builds` property. Please remove one of them.",link:"https://vercel.link/functions-and-builds"});if(config.proxy&&config.builds)return new import_build_utils.NowBuildError({code:"PROXY_AND_BUILDS",message:"The `proxy` property cannot be used with the `builds` property. Remove `builds` to use an explicit proxy entrypoint."});let hasExperimentalServices=!!config.experimentalServices;if(hasExperimentalServices&&config.builds)return new import_build_utils.NowBuildError({code:"EXPERIMENTAL_SERVICES_AND_BUILDS",message:"The `experimentalServices` property cannot be used in conjunction with the `builds` property. Please remove one of them."});if(hasExperimentalServices&&config.functions)return new import_build_utils.NowBuildError({code:"EXPERIMENTAL_SERVICES_AND_FUNCTIONS",message:"The `experimentalServices` property cannot be used in conjunction with the `functions` property. Please remove one of them."});if(config.experimentalServiceGroups&&!config.experimentalServices)return new import_build_utils.NowBuildError({code:"SERVICE_GROUPS_WITHOUT_SERVICES",message:"The `experimentalServiceGroups` property requires `experimentalServices` to be defined. Service groups reference services by name."});let hasServices=config.services!=null,hasExperimentalServicesV2=config.experimentalServicesV2!=null;if(hasServices&&hasExperimentalServicesV2)return new import_build_utils.NowBuildError({code:"SERVICES_AND_EXPERIMENTAL_SERVICES_V2",message:"The `services` property cannot be used in conjunction with its deprecated alias `experimentalServicesV2`. Please use only `services`."});let servicesConfig=config.services??config.experimentalServicesV2,servicesConfigKey=hasServices?"services":"experimentalServicesV2",servicesErrorCodePrefix=hasServices?"SERVICES":"EXPERIMENTAL_SERVICES_V2";if(servicesConfig&&hasExperimentalServices)return new import_build_utils.NowBuildError({code:`${servicesErrorCodePrefix}_AND_EXPERIMENTAL_SERVICES`,message:`The \`${servicesConfigKey}\` property cannot be used in conjunction with the \`experimentalServices\` property. Please use only one services configuration.`});if(servicesConfig&&config.builds)return new import_build_utils.NowBuildError({code:`${servicesErrorCodePrefix}_AND_BUILDS`,message:`The \`${servicesConfigKey}\` property cannot be used in conjunction with the \`builds\` property. Please remove one of them.`});if(servicesConfig){let ambiguousTopLevel=[];if(config.functions!=null&&ambiguousTopLevel.push("functions"),config.installCommand!=null&&ambiguousTopLevel.push("installCommand"),config.buildCommand!=null&&ambiguousTopLevel.push("buildCommand"),config.devCommand!=null&&ambiguousTopLevel.push("devCommand"),config.ignoreCommand!=null&&ambiguousTopLevel.push("ignoreCommand"),config.outputDirectory!=null&&ambiguousTopLevel.push("outputDirectory"),config.framework!=null&&ambiguousTopLevel.push("framework"),ambiguousTopLevel.length>0){let count=ambiguousTopLevel.length,fields=ambiguousTopLevel.map(field=>`\`${field}\``).join(", ");return new import_build_utils.NowBuildError({code:`${servicesErrorCodePrefix}_AND_TOP_LEVEL_BUILD_SETTINGS`,message:`The top-level ${count>1?"properties":"property"} ${fields} cannot be used with \`${servicesConfigKey}\` because the owning service is ambiguous. Move ${count>1?"them":"it"} under the relevant service in \`${servicesConfigKey}\`.`})}}if(config.daemons){let daemonError=validateDaemons(config,config.daemons);if(daemonError)return daemonError}if(servicesConfig){let serviceNames2=new Set(Object.keys(servicesConfig));for(let[serviceName,serviceConfig]of Object.entries(servicesConfig))for(let binding of serviceConfig.bindings??[])if(!serviceNames2.has(binding.service))return scheduleServices.has(binding.service)?scheduleBindingError(config,`Service "${serviceName}"`,binding.service):new import_build_utils.NowBuildError({code:`${servicesErrorCodePrefix}_BINDING_UNKNOWN_SERVICE`,message:`Service "${serviceName}" declares a binding to unknown service "${binding.service}". Add "${binding.service}" to \`${servicesConfigKey}\` or fix the binding.`})}return null}function validateDaemons(config,daemons){let invalid=message=>new import_build_utils.NowBuildError({code:"INVALID_DAEMON",message}),daemonNames=new Set(Object.keys(daemons)),scheduleServices=getScheduleServiceNames(config);for(let[name,daemon]of Object.entries(daemons)){if(!isDockerfilePath(daemon.entrypoint))return invalid(`Daemon "${name}" must set \`entrypoint\` to a Dockerfile or Containerfile.`);if(hasInvalidDockerfileStage(daemon.entrypoint))return invalid(`Daemon "${name}" has invalid \`entrypoint\` "${daemon.entrypoint}". ${import_build_utils.DOCKERFILE_STAGE_HINT}`)}let services={...config.experimentalServicesV2,...config.services},isDaemonTarget=name=>daemonNames.has(name)&&!Object.prototype.hasOwnProperty.call(services,name);for(let[name,service]of Object.entries(services)){let binding=service.bindings?.find(binding2=>isDaemonTarget(binding2.service));if(binding)return invalid(`Service "${name}" cannot bind to daemon "${binding.service}" because daemons do not receive traffic.`)}for(let[name,daemon]of Object.entries(daemons)){let envs=new Set;for(let binding of daemon.bindings??[]){if(!Object.prototype.hasOwnProperty.call(services,binding.service))return scheduleServices.has(binding.service)?scheduleBindingError(config,`Daemon "${name}"`,binding.service):invalid(`Daemon "${name}" declares a binding to unknown service "${binding.service}". Add "${binding.service}" to \`services\` or fix the binding.`);if(envs.has(binding.env))return invalid(`Daemon "${name}" declares more than one binding for the environment variable "${binding.env}".`);envs.add(binding.env)}}let daemonTarget=getDestinationServices(config).find(isDaemonTarget);return daemonTarget?invalid(`Rewrites and routes cannot target daemon "${daemonTarget}" because daemons do not receive traffic.`):null}function getScheduleServiceNames(config){return new Set(Object.entries(config.schedules??{}).filter(([,schedule])=>"entrypoint"in schedule||"run"in schedule).map(([name])=>name))}function invalidScheduleService(config,message){return new import_build_utils.NowBuildError({code:"INVALID_SCHEDULE_SERVICE",message:`Invalid ${config[import_types.fileNameSymbol]||"vercel.json"} - ${message}`})}function scheduleBindingError(config,binder,schedule){return invalidScheduleService(config,`${binder} cannot bind to schedule "${schedule}" because schedules do not receive traffic.`)}function getDestinationServices(config){let services={...config.experimentalServicesV2,...config.services};return[...config.rewrites??[],...config.routes??[],...Object.values(services).flatMap(service=>[...service.rewrites??[],...service.routes??[]])].flatMap(entry=>{let destination="destination"in entry?entry.destination:void 0;return typeof destination=="object"&&destination!==null?[destination.service]:[]})}export{require_constants,require_entrypoint,buildVercelConfigSchema,validateConfig};
7
+ import{require_dist as require_dist2}from"./chunk-VPSR2O55.js";import{require_dist}from"./chunk-ISSNEDG5.js";import{require_types}from"./chunk-AW33SRYY.js";import{require_build_utils}from"./chunk-5MDNVAE6.js";import{__commonJS,__require,__toESM}from"./chunk-BZENIQ7N.js";var require_constants=__commonJS({"../runtimes/dist/constants.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),constants_exports={};__export(constants_exports,{BUILDER_RUNTIMES:()=>BUILDER_RUNTIMES,CONTAINER_ENTRYPOINT_CANDIDATES:()=>CONTAINER_ENTRYPOINT_CANDIDATES,ENTRYPOINT_EXTENSIONS:()=>ENTRYPOINT_EXTENSIONS,ROUTE_OWNING_BUILDERS:()=>ROUTE_OWNING_BUILDERS,RUNTIME_BUILDERS:()=>RUNTIME_BUILDERS,RUNTIME_MANIFESTS:()=>RUNTIME_MANIFESTS,STATIC_BUILDERS:()=>STATIC_BUILDERS});module.exports=__toCommonJS(constants_exports);var RUNTIME_BUILDERS={node:"@vercel/backends",python:"@vercel/python",go:"@vercel/go",rust:"@vercel/rust",ruby:"@vercel/ruby",container:"@vercel/container"},RUNTIME_MANIFESTS={node:["package.json"],python:["pyproject.toml","requirements.txt","Pipfile","pylock.yml","uv.lock","setup.py"],go:["go.mod"],ruby:["Gemfile"],rust:["Cargo.toml"]},ENTRYPOINT_EXTENSIONS={".ts":"node",".mts":"node",".js":"node",".mjs":"node",".cjs":"node",".py":"python",".go":"go",".rs":"rust",".rb":"ruby",".ru":"ruby"},BUILDER_RUNTIMES={...Object.fromEntries(Object.entries(RUNTIME_BUILDERS).map(([runtime,builder])=>[builder,runtime])),"@vercel/node":"node","@vercel/next":"node","@vercel/remix-builder":"node","@vercel/redwood":"node","@vercel/hydrogen":"node","@vercel/express":"node","@vercel/hono":"node","@vercel/h3":"node","@vercel/koa":"node","@vercel/nestjs":"node","@vercel/fastify":"node","@vercel/elysia":"node"},STATIC_BUILDERS=new Set(["@vercel/static-build","@vercel/static"]),ROUTE_OWNING_BUILDERS=new Set(["@vercel/next","@vercel/backends"]),CONTAINER_ENTRYPOINT_CANDIDATES=["Dockerfile.vercel","Containerfile.vercel","Dockerfile","Containerfile"]}});var require_entrypoint=__commonJS({"../runtimes/dist/entrypoint.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),entrypoint_exports={};__export(entrypoint_exports,{isDockerfileEntrypoint:()=>isDockerfileEntrypoint,isNodeScheduleEntrypoint:()=>isNodeScheduleEntrypoint2,parsePyModuleAttrEntrypoint:()=>parsePyModuleAttrEntrypoint,parsePythonScheduleModule:()=>parsePythonScheduleModule2,stripTrailingSlash:()=>stripTrailingSlash});module.exports=__toCommonJS(entrypoint_exports);var import_path=__require("path"),import_constants=require_constants(),PYTHON_MODULE_ATTR_RE=/^([A-Za-z_][\w]*(?:\.[A-Za-z_][\w]*)*):([A-Za-z_][\w]*)$/,PYTHON_MODULE_RE=/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*$/,SOURCE_FILE_RE=/\.(?:py|[cm]?[jt]s)$/,NODE_SOURCE_FILE_RE=/\.(?:m?js|[cm]?ts)$/;function parsePyModuleAttrEntrypoint(entrypoint){let match=PYTHON_MODULE_ATTR_RE.exec(entrypoint);if(!match)return null;let[,modulePart,attrName]=match;return!modulePart||!attrName?null:{attrName,filePath:modulePart.replace(/\./g,"/")+".py",moduleName:modulePart}}function parsePythonScheduleModule2(entrypoint){if(!PYTHON_MODULE_RE.test(entrypoint)||SOURCE_FILE_RE.test(entrypoint))return null;let path=entrypoint.replace(/\./g,"/");return{moduleName:entrypoint,sourceFiles:[`${path}/__init__.py`,`${path}.py`]}}function isNodeScheduleEntrypoint2(entrypoint){return NODE_SOURCE_FILE_RE.test(entrypoint)}var CONTAINER_ENTRYPOINT_BASENAMES=new Set(import_constants.CONTAINER_ENTRYPOINT_CANDIDATES.map(name=>name.toLowerCase()));function isDockerfileEntrypoint(entrypoint){return CONTAINER_ENTRYPOINT_BASENAMES.has(import_path.posix.basename(entrypoint).toLowerCase())}function stripTrailingSlash(p){let stripped=p.replace(/\/+$/,"");return stripped===""?".":stripped}}});var import_routing_utils=__toESM(require_dist(),1),import_build_utils=__toESM(require_build_utils(),1),import_types=__toESM(require_types(),1),import_fs_detectors=__toESM(require_dist2(),1),import_entrypoint=__toESM(require_entrypoint(),1);import{getConfigValidator}from"./config-validator.mjs";var imagesSchema={type:"object",additionalProperties:!1,required:["sizes"],properties:{contentDispositionType:{enum:["inline","attachment"]},contentSecurityPolicy:{type:"string",minLength:1,maxLength:256},dangerouslyAllowSVG:{type:"boolean"},domains:{type:"array",minItems:0,maxItems:50,items:{type:"string",minLength:1,maxLength:256}},formats:{type:"array",minItems:1,maxItems:4,items:{enum:["image/avif","image/webp","image/jpeg","image/png"]}},localPatterns:{type:"array",minItems:0,maxItems:25,items:{type:"object",additionalProperties:!1,properties:{pathname:{type:"string",minLength:1,maxLength:256},search:{type:"string",minLength:0,maxLength:256}}}},minimumCacheTTL:{type:"integer",minimum:1,maximum:31536e4},qualities:{type:"array",minItems:1,maxItems:20,items:{type:"integer",minimum:1,maximum:100}},remotePatterns:{type:"array",minItems:0,maxItems:50,items:{type:"object",additionalProperties:!1,required:["hostname"],properties:{protocol:{enum:["http","https"]},hostname:{type:"string",minLength:1,maxLength:256},port:{type:"string",minLength:0,maxLength:5},pathname:{type:"string",minLength:1,maxLength:256},search:{type:"string",minLength:0,maxLength:256}}}},sizes:{type:"array",minItems:1,maxItems:50,items:{type:"number"}}}},cronsSchema={type:"array",minItems:0,items:{type:"object",additionalProperties:!1,required:["path","schedule"],properties:{path:{type:"string",minLength:1,maxLength:512,pattern:"^/.*"},schedule:{type:"string",minLength:9,maxLength:256}}}},scheduleNameSchema={type:"string",minLength:1,maxLength:256,pattern:"^[0-9A-Za-z][0-9A-Za-z._-]*$"},scheduleDefinitionSchema={type:"object",additionalProperties:!1,properties:{schedule:{type:"string",minLength:9,maxLength:256},timezone:{type:"string",minLength:1,maxLength:50,description:"IANA timezone for cron evaluation. Defaults to UTC."},jitter:{type:"integer",minimum:1,maximum:15},path:{description:"Deployment path to invoke over HTTP, like `crons[].path`. Must start with `/`.",type:"string",maxLength:512,pattern:"^/"},requestMethod:{description:"HTTP method used to invoke `path`. Only valid with `path`. Defaults to `POST`.",enum:["GET","POST"]},function:{type:"string",minLength:1},service:{description:"Service that owns `function`, from `services`. When set, `function` is the path within that service. Only valid with `function`.",type:"string",minLength:1,maxLength:64,pattern:"^[a-z]([a-z_-]*[a-z])?$"},topic:{type:"string",minLength:1,maxLength:256,pattern:"^[A-Za-z0-9_-]+$"},run:{description:"Command to run for each firing. Only valid with a Dockerfile or Containerfile entrypoint.",type:"array",minItems:1,items:[{type:"string",pattern:"\\S"}],additionalItems:{type:"string"}},root:{description:"Directory of the service that runs the schedule's `entrypoint`, which is relative to it. Required with `entrypoint`.",type:"string",minLength:1,maxLength:512},entrypoint:{type:"string",minLength:1,maxLength:512},runtime:{description:"Runtime of an `entrypoint` without `run`: `python` for a module path like `jobs.tasks`, or `node` for a JavaScript or TypeScript file.",enum:["python","node"]}},dependencies:{requestMethod:["path"],service:["function"],run:["entrypoint"],entrypoint:["root"],root:["entrypoint"]},oneOf:[{required:["path"]},{required:["function"]},{required:["topic"]},{required:["entrypoint"]}]},maxSchedules=500,schedulesSchema={type:"object",maxProperties:maxSchedules,propertyNames:scheduleNameSchema,additionalProperties:scheduleDefinitionSchema},experimentalServicesMountSchema={oneOf:[{type:"string",minLength:1,maxLength:512},{type:"object",additionalProperties:!1,properties:{path:{type:"string",minLength:1,maxLength:512},subdomain:{type:"string",minLength:1,maxLength:63}},anyOf:[{required:["path"]},{required:["subdomain"]}]}]},staticExperimentalServiceScheduleSchema={type:"string",minLength:9,maxLength:256,not:{const:"<dynamic>"}},experimentalServiceScheduleSchema={oneOf:[{type:"string",minLength:9,maxLength:256},{type:"array",minItems:1,items:staticExperimentalServiceScheduleSchema}]},experimentalServiceQueueTopicSchema={type:"object",additionalProperties:!1,required:["topic"],properties:{topic:{type:"string",minLength:1,maxLength:256},retryAfterSeconds:{type:"integer",minimum:1,maximum:86400},initialDelaySeconds:{type:"integer",minimum:0,maximum:86400}}},experimentalServiceTopicsSchema={oneOf:[{type:"array",minItems:1,items:{type:"string",minLength:1,maxLength:256}},{type:"array",minItems:1,items:experimentalServiceQueueTopicSchema}]},envVarNamesSchema={pattern:"^[A-Za-z_][A-Za-z0-9_]*$",maxLength:256},getExperimentalServicesCommonProperties=()=>({entrypoint:{type:"string",minLength:1,maxLength:512},root:{type:"string",minLength:1,maxLength:512},workspace:{type:"string",minLength:1,maxLength:512},framework:{type:"string",minLength:1,maxLength:256},builder:{type:"string",minLength:1,maxLength:256},runtime:{type:"string",minLength:1,maxLength:256},buildCommand:{type:"string",minLength:1,maxLength:2048},installCommand:{type:"string",minLength:1,maxLength:2048},preDeployCommand:{type:"string",minLength:1,maxLength:2048},command:{oneOf:[{type:"string",minLength:1,maxLength:2048},{type:"array",minItems:1,items:{type:"string",minLength:1,maxLength:2048}}]},memory:{type:"integer",minimum:128,maximum:10240},maxDuration:(0,import_build_utils.getMaxDurationSchema)(),includeFiles:{oneOf:[{type:"string",minLength:1},{type:"array",items:{type:"string",minLength:1}}]},excludeFiles:{oneOf:[{type:"string",minLength:1},{type:"array",items:{type:"string",minLength:1}}]}}),experimentalServicesRoutableProperties={mount:experimentalServicesMountSchema,routePrefix:{type:"string",minLength:1,maxLength:512},subdomain:{type:"string",minLength:1,maxLength:63}},getExperimentalServicesServiceConfigSchema=()=>({oneOf:[{type:"object",additionalProperties:!1,properties:{...getExperimentalServicesCommonProperties(),...experimentalServicesRoutableProperties,type:{enum:["web"]}}},{type:"object",additionalProperties:!1,required:["type","trigger","schedule"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"job"},trigger:{const:"schedule"},schedule:experimentalServiceScheduleSchema}},{type:"object",additionalProperties:!1,required:["type","trigger","topics"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"job"},trigger:{const:"queue"},topics:experimentalServiceTopicsSchema,consumer:{type:"string",minLength:1,maxLength:256}}},{type:"object",additionalProperties:!1,required:["type","trigger","entrypoint"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"job"},trigger:{const:"workflow"}}},{type:"object",additionalProperties:!1,required:["type"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"worker"},topics:{type:"array",items:{type:"string",minLength:1,maxLength:256},minItems:1},consumer:{type:"string",minLength:1,maxLength:256}}},{type:"object",additionalProperties:!1,required:["type","schedule"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"cron"},schedule:experimentalServiceScheduleSchema}}]}),getExperimentalServicesSchema=()=>({type:"object",propertyNames:{pattern:"^[a-zA-Z]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$",maxLength:64},additionalProperties:getExperimentalServicesServiceConfigSchema()}),experimentalServiceGroupsSchema={type:"object",propertyNames:{pattern:"^[a-zA-Z]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$",maxLength:64},additionalProperties:{type:"array",items:{type:"string",minLength:1,maxLength:256}}},servicesPathSchema={type:"string",minLength:1,maxLength:512},servicesCommandSchema={type:"string",minLength:1,maxLength:2048},servicesBindingSchema={type:"object",additionalProperties:!1,required:["service","format","env"],properties:{type:{description:"Optional binding type marker. Currently the only supported type is `service`. When present this must be `service`.",const:"service"},service:{type:"string",minLength:1,maxLength:64,pattern:import_build_utils.SERVICE_NAME_PATTERN},format:{const:"url"},env:{type:"string",...envVarNamesSchema}}},servicesBindingsSchema={type:"array",maxItems:100,items:servicesBindingSchema},getServicesServiceConfigSchema=()=>({type:"object",additionalProperties:!1,required:["root"],properties:{root:servicesPathSchema,framework:{type:"string",minLength:1,maxLength:256},runtime:{type:"string",minLength:1,maxLength:256},entrypoint:servicesPathSchema,command:{oneOf:[{type:"string",minLength:1,maxLength:4096},{type:"array",minItems:1,maxItems:128,items:{type:"string",minLength:1,maxLength:4096}}]},installCommand:servicesCommandSchema,buildCommand:servicesCommandSchema,devCommand:servicesCommandSchema,ignoreCommand:servicesCommandSchema,outputDirectory:servicesPathSchema,bindings:servicesBindingsSchema,functions:(0,import_build_utils.getFunctionsSchema)(),headers:import_routing_utils.headersSchema,redirects:import_routing_utils.redirectsSchema,rewrites:import_routing_utils.rewritesSchema,routes:import_routing_utils.routesSchema,cleanUrls:import_routing_utils.cleanUrlsSchema,trailingSlash:import_routing_utils.trailingSlashSchema}}),daemonConfigSchema={type:"object",additionalProperties:!1,required:["root","entrypoint"],anyOf:[{required:["instances"]},{required:["replicas"]}],properties:{root:servicesPathSchema,entrypoint:servicesPathSchema,command:{type:"array",minItems:1,maxItems:128,items:{type:"string",minLength:1,maxLength:4096}},instances:{type:"object",additionalProperties:{type:"integer",minimum:0}},replicas:{description:"Deprecated. Use `instances`. Ignored when `instances` is set.",deprecated:!0,type:"object",additionalProperties:{type:"integer",minimum:0}},resources:{type:"object",additionalProperties:!1,required:["requests"],properties:{requests:{type:"object",additionalProperties:!1,required:["memory"],properties:{memory:{enum:["1Gi","2Gi","4Gi","8Gi"]}}}}},terminationGracePeriodSeconds:{type:"integer",minimum:0},livenessProbe:{type:"object",additionalProperties:!1,required:["httpGet"],properties:{httpGet:{type:"object",additionalProperties:!1,required:["port"],properties:{path:{type:"string",minLength:1},port:{type:"integer",minimum:1,maximum:65535},host:{type:"string",minLength:1},scheme:{enum:["HTTP","HTTPS"]},httpHeaders:{type:"array",items:{type:"object",additionalProperties:!1,required:["name","value"],properties:{name:{type:"string",minLength:1},value:{type:"string"}}}}}},initialDelaySeconds:{type:"integer",minimum:0,maximum:86400},periodSeconds:{type:"integer",minimum:1,maximum:86400},timeoutSeconds:{type:"integer",minimum:1,maximum:86400},successThreshold:{type:"integer",minimum:1,maximum:10},failureThreshold:{type:"integer",minimum:1,maximum:10}}},bindings:{...servicesBindingsSchema,items:{...servicesBindingSchema,required:["type",...servicesBindingSchema.required]}}}},getServicesSchema=()=>({type:"object",propertyNames:{pattern:import_build_utils.SERVICE_NAME_PATTERN,maxLength:64},additionalProperties:getServicesServiceConfigSchema()}),maxDaemons=100,daemonsSchema={type:"object",maxProperties:maxDaemons,propertyNames:{pattern:import_build_utils.DAEMON_NAME_PATTERN,maxLength:64},additionalProperties:daemonConfigSchema},proxySchema={type:"object",additionalProperties:!1,required:["entrypoint"],properties:{entrypoint:{type:"string",minLength:1},matcher:{oneOf:[{type:"string",minLength:1},{type:"array",minItems:1,items:{type:"string",minLength:1}}]}}};function buildVercelConfigSchema(){return{type:"object",additionalProperties:!0,properties:{builds:import_build_utils.buildsSchema,routes:import_routing_utils.routesSchema,cleanUrls:import_routing_utils.cleanUrlsSchema,headers:import_routing_utils.headersSchema,redirects:import_routing_utils.redirectsSchema,rewrites:import_routing_utils.rewritesSchema,trailingSlash:import_routing_utils.trailingSlashSchema,functions:(0,import_build_utils.getFunctionsSchema)(),images:imagesSchema,crons:cronsSchema,schedules:schedulesSchema,bunVersion:{type:"string"},proxy:proxySchema,experimentalServices:getExperimentalServicesSchema(),experimentalServiceGroups:experimentalServiceGroupsSchema,services:getServicesSchema(),experimentalServicesV2:getServicesSchema(),daemons:daemonsSchema}}}var isDockerfilePath=entrypoint=>/(docker|container)file/i.test((0,import_build_utils.splitDockerfileEntrypoint)(entrypoint).path.split(/[\\/]/).pop()??""),toPythonModulePath=entrypoint=>entrypoint.replace(/\.py$/,"").replace(/[\\/]+/g,".").replace(/(^|\.)__init__$/,""),hasInvalidDockerfileStage=entrypoint=>{let{buildTarget}=(0,import_build_utils.splitDockerfileEntrypoint)(entrypoint);return buildTarget!==void 0&&!(0,import_build_utils.isValidDockerfileStage)(buildTarget)};function validateConfig(config){let validate=getConfigValidator(buildVercelConfigSchema);if(!validate(config)&&validate.errors&&validate.errors[0]){let error=validate.errors[0],fileName=config[import_types.fileNameSymbol]||"vercel.json",niceError=(0,import_build_utils.getPrettyError)(error);return niceError.message=`Invalid ${fileName} - ${niceError.message}`,niceError}let serviceNames=new Set([...Object.keys(config.services??{}),...Object.keys(config.daemons??{})]),scheduleServices=getScheduleServiceNames(config),destinationServices=new Set(getDestinationServices(config)),invalidSchedule=(code,message)=>new import_build_utils.NowBuildError({code,message:`Invalid ${config[import_types.fileNameSymbol]||"vercel.json"} - ${message}`}),invalidCommand=message=>invalidSchedule("INVALID_SCHEDULE_COMMAND",message),invalidEntrypoint=message=>invalidSchedule("INVALID_SCHEDULE_ENTRYPOINT",message);for(let[name,schedule]of Object.entries(config.schedules??{})){let path=`schedules.${name}`;if("runtime"in schedule&&("run"in schedule||!("entrypoint"in schedule)))return invalidEntrypoint(`\`${path}.runtime\` is only valid with an \`entrypoint\` and without \`run\`.`);if("entrypoint"in schedule&&!("run"in schedule)){let{entrypoint,runtime}=schedule;if(!runtime)return isDockerfilePath(entrypoint)?invalidEntrypoint(`\`${path}.entrypoint\` names a Dockerfile, so \`${path}\` must set \`run\`.`):invalidEntrypoint(`\`${path}\` must set \`runtime\` to run its \`entrypoint\`: "python" for a module path like "jobs.tasks", or "node" for a .js, .mjs, .ts, .mts or .cts file.`);if(runtime==="python"&&!(0,import_entrypoint.parsePythonScheduleModule)(entrypoint)){let suggestion=entrypoint.endsWith(".py")?toPythonModulePath(entrypoint):"";return invalidEntrypoint(`\`${path}.entrypoint\` "${entrypoint}" must be a Python module path like "${(0,import_entrypoint.parsePythonScheduleModule)(suggestion)?suggestion:"jobs.tasks"}", since \`${path}.runtime\` is "python".`)}if(runtime==="node"&&!(0,import_entrypoint.isNodeScheduleEntrypoint)(entrypoint))return invalidEntrypoint(`\`${path}.entrypoint\` "${entrypoint}" must be a .js, .mjs, .ts, .mts or .cts file, since \`${path}.runtime\` is "node".`);let configured=["schedule","timezone","jitter"].find(key=>key in schedule);if(configured)return invalidEntrypoint(runtime==="node"?`\`${path}\` runs "${entrypoint}", whose \`export const config\` sets its cron, timezone and jitter. Remove \`${path}.${configured}\`.`:`\`${path}\` runs the Python module "${entrypoint}", whose \`@schedule\` handlers set their own cron, timezone and jitter. Remove \`${path}.${configured}\`.`)}else if(!("schedule"in schedule))return invalidSchedule("INVALID_SCHEDULE_EXPRESSION",`\`${path}\` is missing required property \`schedule\`.`);if("run"in schedule){if(!isDockerfilePath(schedule.entrypoint))return invalidCommand(`\`${path}.run\` requires a Dockerfile or Containerfile \`entrypoint\`.`);if(hasInvalidDockerfileStage(schedule.entrypoint))return invalidCommand(`\`${path}.entrypoint\` "${schedule.entrypoint}" is invalid. ${import_build_utils.DOCKERFILE_STAGE_HINT}`)}if(scheduleServices.has(name)){if(name.length>64||!new RegExp(import_build_utils.SERVICE_NAME_PATTERN).test(name))return invalidScheduleService(config,`\`${path}\` runs as a service, so its name must be a valid service name: lowercase letters, \`-\` and \`_\`, at most 64 characters.`);if(serviceNames.has(name))return invalidScheduleService(config,`\`${path}\` runs as service "${name}", which is already the name of a service or daemon.`);if(destinationServices.has(name))return invalidScheduleService(config,`Rewrites and routes cannot target schedule "${name}" because schedules do not receive traffic.`)}if(!(!("timezone"in schedule)||schedule.timezone===void 0))try{if(!/^[A-Za-z][A-Za-z0-9_+/-]*$/.test(schedule.timezone))throw new RangeError("Expected a named timezone");new Intl.DateTimeFormat("en-US",{timeZone:schedule.timezone})}catch{return new import_build_utils.NowBuildError({code:"INVALID_SCHEDULE_TIMEZONE",message:`Invalid ${config[import_types.fileNameSymbol]||"vercel.json"} - \`schedules.${name}.timezone\` must be a valid IANA timezone, such as "America/New_York". Omit it to use UTC.`})}}let functionMaps=[config.functions,...Object.values(config.services??{}).map(service=>service.functions),...Object.values(config.experimentalServicesV2??{}).map(service=>service.functions)];for(let functions of functionMaps)for(let[pattern,fn]of Object.entries(functions??{})){let regions=[...new Set(fn.regions)];if(fn.affinity?.mode==="strict"&&(regions.includes("all")||regions.length>1))return new import_build_utils.NowBuildError({code:"INVALID_FUNCTION_AFFINITY_REGIONS",message:`Function affinity mode "strict" requires at most one statically configured region. Update \`functions[${JSON.stringify(pattern)}].regions\` to contain a single region.`,link:"https://vercel.com/docs/concepts/projects/project-configuration#functions"})}if(config.proxy){let proxyError=(0,import_fs_detectors.validateProxyConfig)(config.proxy);if(proxyError)return new import_build_utils.NowBuildError({code:proxyError.code.toUpperCase(),message:proxyError.message})}if(config.functions&&config.builds)return new import_build_utils.NowBuildError({code:"FUNCTIONS_AND_BUILDS",message:"The `functions` property cannot be used in conjunction with the `builds` property. Please remove one of them.",link:"https://vercel.link/functions-and-builds"});if(config.proxy&&config.builds)return new import_build_utils.NowBuildError({code:"PROXY_AND_BUILDS",message:"The `proxy` property cannot be used with the `builds` property. Remove `builds` to use an explicit proxy entrypoint."});let hasExperimentalServices=!!config.experimentalServices;if(hasExperimentalServices&&config.builds)return new import_build_utils.NowBuildError({code:"EXPERIMENTAL_SERVICES_AND_BUILDS",message:"The `experimentalServices` property cannot be used in conjunction with the `builds` property. Please remove one of them."});if(hasExperimentalServices&&config.functions)return new import_build_utils.NowBuildError({code:"EXPERIMENTAL_SERVICES_AND_FUNCTIONS",message:"The `experimentalServices` property cannot be used in conjunction with the `functions` property. Please remove one of them."});if(config.experimentalServiceGroups&&!config.experimentalServices)return new import_build_utils.NowBuildError({code:"SERVICE_GROUPS_WITHOUT_SERVICES",message:"The `experimentalServiceGroups` property requires `experimentalServices` to be defined. Service groups reference services by name."});let hasServices=config.services!=null,hasExperimentalServicesV2=config.experimentalServicesV2!=null;if(hasServices&&hasExperimentalServicesV2)return new import_build_utils.NowBuildError({code:"SERVICES_AND_EXPERIMENTAL_SERVICES_V2",message:"The `services` property cannot be used in conjunction with its deprecated alias `experimentalServicesV2`. Please use only `services`."});let servicesConfig=config.services??config.experimentalServicesV2,servicesConfigKey=hasServices?"services":"experimentalServicesV2",servicesErrorCodePrefix=hasServices?"SERVICES":"EXPERIMENTAL_SERVICES_V2";if(servicesConfig&&hasExperimentalServices)return new import_build_utils.NowBuildError({code:`${servicesErrorCodePrefix}_AND_EXPERIMENTAL_SERVICES`,message:`The \`${servicesConfigKey}\` property cannot be used in conjunction with the \`experimentalServices\` property. Please use only one services configuration.`});if(servicesConfig&&config.builds)return new import_build_utils.NowBuildError({code:`${servicesErrorCodePrefix}_AND_BUILDS`,message:`The \`${servicesConfigKey}\` property cannot be used in conjunction with the \`builds\` property. Please remove one of them.`});if(servicesConfig){let ambiguousTopLevel=[];if(config.functions!=null&&ambiguousTopLevel.push("functions"),config.installCommand!=null&&ambiguousTopLevel.push("installCommand"),config.buildCommand!=null&&ambiguousTopLevel.push("buildCommand"),config.devCommand!=null&&ambiguousTopLevel.push("devCommand"),config.ignoreCommand!=null&&ambiguousTopLevel.push("ignoreCommand"),config.outputDirectory!=null&&ambiguousTopLevel.push("outputDirectory"),config.framework!=null&&ambiguousTopLevel.push("framework"),ambiguousTopLevel.length>0){let count=ambiguousTopLevel.length,fields=ambiguousTopLevel.map(field=>`\`${field}\``).join(", ");return new import_build_utils.NowBuildError({code:`${servicesErrorCodePrefix}_AND_TOP_LEVEL_BUILD_SETTINGS`,message:`The top-level ${count>1?"properties":"property"} ${fields} cannot be used with \`${servicesConfigKey}\` because the owning service is ambiguous. Move ${count>1?"them":"it"} under the relevant service in \`${servicesConfigKey}\`.`})}}if(config.daemons){let daemonError=validateDaemons(config,config.daemons);if(daemonError)return daemonError}if(servicesConfig){let serviceNames2=new Set(Object.keys(servicesConfig));for(let[serviceName,serviceConfig]of Object.entries(servicesConfig))for(let binding of serviceConfig.bindings??[])if(!serviceNames2.has(binding.service))return scheduleServices.has(binding.service)?scheduleBindingError(config,`Service "${serviceName}"`,binding.service):new import_build_utils.NowBuildError({code:`${servicesErrorCodePrefix}_BINDING_UNKNOWN_SERVICE`,message:`Service "${serviceName}" declares a binding to unknown service "${binding.service}". Add "${binding.service}" to \`${servicesConfigKey}\` or fix the binding.`})}return null}function validateDaemons(config,daemons){let invalid=message=>new import_build_utils.NowBuildError({code:"INVALID_DAEMON",message}),daemonNames=new Set(Object.keys(daemons)),scheduleServices=getScheduleServiceNames(config);for(let[name,daemon]of Object.entries(daemons)){if(!isDockerfilePath(daemon.entrypoint))return invalid(`Daemon "${name}" must set \`entrypoint\` to a Dockerfile or Containerfile.`);if(hasInvalidDockerfileStage(daemon.entrypoint))return invalid(`Daemon "${name}" has invalid \`entrypoint\` "${daemon.entrypoint}". ${import_build_utils.DOCKERFILE_STAGE_HINT}`)}let services={...config.experimentalServicesV2,...config.services},isDaemonTarget=name=>daemonNames.has(name)&&!Object.prototype.hasOwnProperty.call(services,name);for(let[name,service]of Object.entries(services)){let binding=service.bindings?.find(binding2=>isDaemonTarget(binding2.service));if(binding)return invalid(`Service "${name}" cannot bind to daemon "${binding.service}" because daemons do not receive traffic.`)}for(let[name,daemon]of Object.entries(daemons)){let envs=new Set;for(let binding of daemon.bindings??[]){if(!Object.prototype.hasOwnProperty.call(services,binding.service))return scheduleServices.has(binding.service)?scheduleBindingError(config,`Daemon "${name}"`,binding.service):invalid(`Daemon "${name}" declares a binding to unknown service "${binding.service}". Add "${binding.service}" to \`services\` or fix the binding.`);if(envs.has(binding.env))return invalid(`Daemon "${name}" declares more than one binding for the environment variable "${binding.env}".`);envs.add(binding.env)}}let daemonTarget=getDestinationServices(config).find(isDaemonTarget);return daemonTarget?invalid(`Rewrites and routes cannot target daemon "${daemonTarget}" because daemons do not receive traffic.`):null}function getScheduleServiceNames(config){return new Set(Object.entries(config.schedules??{}).filter(([,schedule])=>"entrypoint"in schedule||"run"in schedule).map(([name])=>name))}function invalidScheduleService(config,message){return new import_build_utils.NowBuildError({code:"INVALID_SCHEDULE_SERVICE",message:`Invalid ${config[import_types.fileNameSymbol]||"vercel.json"} - ${message}`})}function scheduleBindingError(config,binder,schedule){return invalidScheduleService(config,`${binder} cannot bind to schedule "${schedule}" because schedules do not receive traffic.`)}function getDestinationServices(config){let services={...config.experimentalServicesV2,...config.services};return[...config.rewrites??[],...config.routes??[],...Object.values(services).flatMap(service=>[...service.rewrites??[],...service.routes??[]])].flatMap(entry=>{let destination="destination"in entry?entry.destination:void 0;return typeof destination=="object"&&destination!==null?[destination.service]:[]})}export{require_constants,require_entrypoint,buildVercelConfigSchema,validateConfig};
@@ -4,17 +4,17 @@ 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,stringify}from"./chunk-U4Z2MMOF.js";import{applyEdits,init_main,modify,parse as parse2,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-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
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)}
11
11
  `;let merged=deepMerge(raw,patch),modifyOptions=current.trim().includes(`
12
12
  `)?{formattingOptions:detectJsonFormatting(current)}:{};try{let text=current,splice=(existing,subPatch,path)=>{for(let[key,patchValue]of Object.entries(subPatch)){let existingValue=existing?.[key];isPlainObject(patchValue)&&isPlainObject(existingValue)?splice(existingValue,patchValue,[...path,key]):isDeepStrictEqual(existingValue,patchValue)||(text=applyEdits(text,modify(text,[...path,key],patchValue,modifyOptions)))}};if(splice(raw,patch,[]),isDeepStrictEqual(parse4(text),merged))return text}catch{}return`${JSON.stringify(merged,null,2)}
13
- `}function mergeJsonc(current,patch){return mergeJson(current,patch,text=>{let errors=[],value=parse2(text,errors,{allowTrailingComma:!0}),first=errors[0];if(first)throw new Error(`${printParseErrorCode(first.error)} at offset ${first.offset}`);return value})}function patchSatisfied(existing,patch){for(let[key,patchValue]of Object.entries(patch)){let existingValue=isPlainObject(existing)?existing[key]:void 0;if(isPlainObject(patchValue)&&isPlainObject(existingValue)){if(!patchSatisfied(existingValue,patchValue))return!1}else if(!isDeepStrictEqual(existingValue,patchValue))return!1}return!0}function tomlScalar(value){switch(typeof value){case"string":return JSON.stringify(value);case"number":return Number.isFinite(value)?String(value):null;case"boolean":return String(value);default:return null}}var TOML_BARE_KEY=/^[A-Za-z0-9_-]+$/;function flattenTomlPatch(patch,prefix="",out=new Map){for(let[key,value]of Object.entries(patch)){if(!TOML_BARE_KEY.test(key))return null;if(isPlainObject(value)){if(!flattenTomlPatch(value,prefix?`${prefix}.${key}`:key,out))return null}else{let scalar=tomlScalar(value);if(scalar===null)return null;let section=out.get(prefix);section||(section=new Map,out.set(prefix,section)),section.set(key,scalar)}}return out}var TOML_HEADER=/^\s*\[\[?\s*([^\]]*?)\s*\]\]?\s*(?:#.*)?$/;function mergeToml(current,patch){let parsed={};if(current&&current.trim())try{parsed=parse(current)}catch(err){throw new Error(`existing file is not valid TOML (${err.message})`)}let legacy=()=>`${stringify(deepMerge(parsed,patch))}
13
+ `}function mergeJsonc(current,patch){return mergeJson(current,patch,text=>{let errors=[],value=parse(text,errors,{allowTrailingComma:!0}),first=errors[0];if(first)throw new Error(`${printParseErrorCode(first.error)} at offset ${first.offset}`);return value})}function patchSatisfied(existing,patch){for(let[key,patchValue]of Object.entries(patch)){let existingValue=isPlainObject(existing)?existing[key]:void 0;if(isPlainObject(patchValue)&&isPlainObject(existingValue)){if(!patchSatisfied(existingValue,patchValue))return!1}else if(!isDeepStrictEqual(existingValue,patchValue))return!1}return!0}function tomlScalar(value){switch(typeof value){case"string":return JSON.stringify(value);case"number":return Number.isFinite(value)?String(value):null;case"boolean":return String(value);default:return null}}var TOML_BARE_KEY=/^[A-Za-z0-9_-]+$/;function flattenTomlPatch(patch,prefix="",out=new Map){for(let[key,value]of Object.entries(patch)){if(!TOML_BARE_KEY.test(key))return null;if(isPlainObject(value)){if(!flattenTomlPatch(value,prefix?`${prefix}.${key}`:key,out))return null}else{let scalar=tomlScalar(value);if(scalar===null)return null;let section=out.get(prefix);section||(section=new Map,out.set(prefix,section)),section.set(key,scalar)}}return out}var TOML_HEADER=/^\s*\[\[?\s*([^\]]*?)\s*\]\]?\s*(?:#.*)?$/;function mergeToml(current,patch){let parsed={};if(current&&current.trim())try{parsed=parse2(current)}catch(err){throw new Error(`existing file is not valid TOML (${err.message})`)}let legacy=()=>`${stringify(deepMerge(parsed,patch))}
14
14
  `;if(!current||!current.trim())return legacy();if(patchSatisfied(parsed,patch))return current;let flat=flattenTomlPatch(patch);if(!flat)return legacy();let crlf=current.includes(`\r
15
15
  `),lines=current.split(`
16
16
  `),content=line=>line.endsWith("\r")?line.slice(0,-1):line,finish=(line,i)=>i<lines.length&&lines[i]?.endsWith("\r")?`${line}\r`:line,headerAt=i=>{let m=content(lines[i]).match(TOML_HEADER);return m?m[1].split(".").map(s=>s.trim()).join("."):null},sectionRange=name=>{let start=name===""?0:-1;for(let i=0;i<lines.length;i++){let header=headerAt(i);if(header!==null){if(start!==-1)return[start,i];if(name==="")return[0,i];header===name&&(start=i+1)}}return start===-1?null:[start,lines.length]},appendSections=[];for(let[name,keys]of flat){let range=sectionRange(name);if(!range){appendSections.push(`[${name}]`,...[...keys].map(([k,v])=>`${k} = ${v}`));continue}let[start,end]=range,inserts=[];for(let[key,value]of keys){let assignment=new RegExp(`^(\\s*)${key}\\s*=`),replaced=!1;for(let i=start;i<end;i++){let m=content(lines[i]).match(assignment);if(m){lines[i]=finish(`${m[1]}${key} = ${value}`,i),replaced=!0;break}}replaced||inserts.push(`${key} = ${value}`)}if(inserts.length>0){let at=start;for(let i=start;i<end;i++)content(lines[i]).trim()!==""&&(at=i+1);lines.splice(at,0,...inserts.map(l=>finish(l,at)))}}if(appendSections.length>0){for(;lines.length>0&&content(lines[lines.length-1]).trim()==="";)lines.pop();let eol=crlf?"\r":"";lines.push(...["",...appendSections,""].map(l=>l===""?l:`${l}${eol}`))}let result=lines.join(`
17
- `);try{if(isDeepStrictEqual(parse(result),deepMerge(parsed,patch)))return result}catch{}return legacy()}var MANAGED_BLOCK_START="# >>> vercel ai-gateway >>>",MANAGED_BLOCK_END="# <<< vercel ai-gateway <<<";function upsertManagedBlock(current,body){let block=`${MANAGED_BLOCK_START}
17
+ `);try{if(isDeepStrictEqual(parse2(result),deepMerge(parsed,patch)))return result}catch{}return legacy()}var MANAGED_BLOCK_START="# >>> vercel ai-gateway >>>",MANAGED_BLOCK_END="# <<< vercel ai-gateway <<<";function upsertManagedBlock(current,body){let block=`${MANAGED_BLOCK_START}
18
18
  ${body}
19
19
  ${MANAGED_BLOCK_END}`,existing=current??"",start=existing.indexOf(MANAGED_BLOCK_START),end=existing.indexOf(MANAGED_BLOCK_END);if(start!==-1&&end!==-1&&end>start){let before=existing.slice(0,start),after=existing.slice(end+MANAGED_BLOCK_END.length);return`${before}${block}${after}`}if(existing.length===0)return`${block}
20
20
  `;let prefix=existing.endsWith(`
@@ -30,4 +30,4 @@ ${MANAGED_BLOCK_END}`,existing=current??"",start=existing.indexOf(MANAGED_BLOCK_
30
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
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(" ")}
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=parse(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 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};
@@ -4,5 +4,5 @@ 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{canPrompt}from"./chunk-IQ7FPAI4.js";import{AGENT_REASON,AGENT_STATUS,outputActionRequired}from"./chunk-M2GHHK7B.js";import{humanizePath,require_lib}from"./chunk-IBZJP22D.js";import{output_manager_default}from"./chunk-AP6DZGTK.js";import{require_source}from"./chunk-NB2WLB3J.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_fs_extra=__toESM(require_lib(),1),import_chalk=__toESM(require_source(),1);import{homedir}from"os";import{resolve,sep}from"path";async function validateRootDirectory(cwd,path,errorSuffix=""){let pathStat=await(0,import_fs_extra.lstat)(path).catch(()=>null),suffix=errorSuffix?` ${errorSuffix}`:"";if(!pathStat)return output_manager_default.error(`The provided path ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)} does not exist.${suffix}`),!1;if(!pathStat.isDirectory())return output_manager_default.error(`The provided path ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)} is a file, but expected a directory.${suffix}`),!1;let base=resolve(cwd),target=resolve(path);return target!==base&&!target.startsWith(base+sep)?(output_manager_default.error(`The provided path ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)} is outside of the project.${suffix}`),!1):!0}async function validatePaths(client,paths,{allowFiles=!1}={}){if(paths.length>1)return output_manager_default.error("Can't deploy more than one path."),{valid:!1,exitCode:1};let path=paths[0],pathStat=await(0,import_fs_extra.lstat)(path).catch(()=>null);if(!pathStat)return output_manager_default.error(`Could not find ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)}`),{valid:!1,exitCode:1};let isFile=pathStat.isFile();if(!pathStat.isDirectory()&&!(allowFiles&&isFile))return output_manager_default.fatal(allowFiles?"Deploy a regular file or directory. Symbolic links and special files are not supported as deployment paths.":"This command requires a directory. Use `vercel <file>` to deploy a single file."),{valid:!1,exitCode:1};if(path===homedir()){if(!canPrompt(client)){let message="Can't deploy your home directory without interactive confirmation. Run from your project directory, or run in a terminal to confirm deploying your home directory.";return outputActionRequired(client,{status:AGENT_STATUS.ACTION_REQUIRED,reason:AGENT_REASON.INTERACTIVE_CONFIRMATION_REQUIRED,message,userActionRequired:!0},2),output_manager_default.error(message),{valid:!1,exitCode:2}}if(!await client.input.confirm("You are deploying your home directory. Do you want to continue?",!1))return output_manager_default.print(`Canceled
7
+ import{canPrompt}from"./chunk-IQ7FPAI4.js";import{humanizePath,require_lib}from"./chunk-Z2KANBOU.js";import{AGENT_REASON,AGENT_STATUS,outputActionRequired}from"./chunk-4SS6W6JK.js";import{output_manager_default}from"./chunk-AP6DZGTK.js";import{require_source}from"./chunk-NB2WLB3J.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_fs_extra=__toESM(require_lib(),1),import_chalk=__toESM(require_source(),1);import{homedir}from"os";import{resolve,sep}from"path";async function validateRootDirectory(cwd,path,errorSuffix=""){let pathStat=await(0,import_fs_extra.lstat)(path).catch(()=>null),suffix=errorSuffix?` ${errorSuffix}`:"";if(!pathStat)return output_manager_default.error(`The provided path ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)} does not exist.${suffix}`),!1;if(!pathStat.isDirectory())return output_manager_default.error(`The provided path ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)} is a file, but expected a directory.${suffix}`),!1;let base=resolve(cwd),target=resolve(path);return target!==base&&!target.startsWith(base+sep)?(output_manager_default.error(`The provided path ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)} is outside of the project.${suffix}`),!1):!0}async function validatePaths(client,paths,{allowFiles=!1}={}){if(paths.length>1)return output_manager_default.error("Can't deploy more than one path."),{valid:!1,exitCode:1};let path=paths[0],pathStat=await(0,import_fs_extra.lstat)(path).catch(()=>null);if(!pathStat)return output_manager_default.error(`Could not find ${import_chalk.default.cyan(`\u201C${humanizePath(path)}\u201D`)}`),{valid:!1,exitCode:1};let isFile=pathStat.isFile();if(!pathStat.isDirectory()&&!(allowFiles&&isFile))return output_manager_default.fatal(allowFiles?"Deploy a regular file or directory. Symbolic links and special files are not supported as deployment paths.":"This command requires a directory. Use `vercel <file>` to deploy a single file."),{valid:!1,exitCode:1};if(path===homedir()){if(!canPrompt(client)){let message="Can't deploy your home directory without interactive confirmation. Run from your project directory, or run in a terminal to confirm deploying your home directory.";return outputActionRequired(client,{status:AGENT_STATUS.ACTION_REQUIRED,reason:AGENT_REASON.INTERACTIVE_CONFIRMATION_REQUIRED,message,userActionRequired:!0},2),output_manager_default.error(message),{valid:!1,exitCode:2}}if(!await client.input.confirm("You are deploying your home directory. Do you want to continue?",!1))return output_manager_default.print(`Canceled
8
8
  `),{valid:!1,exitCode:0}}return{valid:!0,path,isFile}}export{validateRootDirectory,validatePaths};
@@ -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{getResolvedOrderMetadata,getRollupColumnName}from"./chunk-NKWA7NQP.js";import{formatGranularity}from"./chunk-IVSSTHB6.js";import{ellipsizeMiddle}from"./chunk-TOTTVS5P.js";import{elapsed}from"./chunk-Q7D7RGXM.js";import{indent_default}from"./chunk-GZNDA6SV.js";import{table}from"./chunk-CJZE7647.js";import{require_ms}from"./chunk-MXTC4ZAQ.js";import{remoteText}from"./chunk-GLIQ4KNY.js";import{require_source}from"./chunk-NB2WLB3J.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_ms=__toESM(require_ms(),1),MINUTE_MS=60*1e3,HOUR_MS=60*MINUTE_MS,DAY_MS=24*HOUR_MS;function toGranularityDuration(input){let milliseconds=(0,import_ms.default)(input);if(milliseconds===void 0)throw new Error(`Invalid granularity format "${input}". Use 1m, 5m, 15m, 1h, 4h, 1d.`);return milliseconds>=DAY_MS?{days:milliseconds/DAY_MS}:milliseconds>=HOUR_MS?{hours:milliseconds/HOUR_MS}:{minutes:milliseconds/MINUTE_MS}}function toGranularityMs(input){let milliseconds=(0,import_ms.default)(input);if(milliseconds===void 0)throw new Error(`Invalid granularity format "${input}".`);return milliseconds}var GRANULARITY_THRESHOLDS=[[1*HOUR_MS,"1m","1m"],[2*HOUR_MS,"5m","5m"],[12*HOUR_MS,"15m","5m"],[3*DAY_MS,"1h","1h"],[30*DAY_MS,"4h","4h"]],FALLBACK_GRANULARITY="1d";function getAutoGranularity(rangeMs){for(let[maxRange,defaultG]of GRANULARITY_THRESHOLDS)if(rangeMs<=maxRange)return defaultG;return FALLBACK_GRANULARITY}function getMinGranularity(rangeMs){for(let[maxRange,,minG]of GRANULARITY_THRESHOLDS)if(rangeMs<=maxRange)return minG;return FALLBACK_GRANULARITY}function computeGranularity(rangeMs,explicit){if(!explicit){let auto=getAutoGranularity(rangeMs);return{duration:toGranularityDuration(auto),adjusted:!1}}let minG=getMinGranularity(rangeMs),explicitMs=toGranularityMs(explicit),minMs=toGranularityMs(minG);if(explicitMs<minMs){let rangeDays=Math.round(rangeMs/DAY_MS),rangeHours=Math.round(rangeMs/HOUR_MS),rangeLabel=rangeDays>=1?`${rangeDays}-day`:`${rangeHours}-hour`;return{duration:toGranularityDuration(minG),adjusted:!0,notice:`Granularity adjusted from ${explicit} to ${minG} for a ${rangeLabel} time range.`}}return{duration:toGranularityDuration(explicit),adjusted:!1}}function toGranularityMsFromDuration(duration){return"minutes"in duration?duration.minutes*MINUTE_MS:"hours"in duration?duration.hours*HOUR_MS:duration.days*DAY_MS}var CANONICAL_AGGREGATIONS=["count","sum","avg","min","max","p50","p75","p90","p95","p99","stddev"];function isCanonicalAggregation(aggregation){return CANONICAL_AGGREGATIONS.includes(aggregation)}var DURATION_UNITS=new Set(["nanoseconds","microseconds","milliseconds","seconds","minutes","hours","days"]);function normalizeMetricUnit(unit){return unit.trim().toLowerCase().replace(/[_\s]+/g," ")}function getPreferredCustomMetricAggregation(unit){let normalizedUnit=normalizeMetricUnit(unit);return DURATION_UNITS.has(normalizedUnit)?"p75":normalizedUnit==="percent"?"avg":"sum"}function getDefaultCustomMetricAggregation(unit,aggregations){let preferredAggregation=getPreferredCustomMetricAggregation(unit);return aggregations?.includes(preferredAggregation)?preferredAggregation:aggregations?.includes("sum")?"sum":aggregations?.find(isCanonicalAggregation)}var import_chalk=__toESM(require_source(),1);var GROUP_KEY_DELIMITER="",MAX_SPARKLINE_LENGTH=120,MAX_HEADER_PROJECTS=5,DURATION_SCALE_MS={seconds:1e3,minutes:6e4,hours:36e5,days:864e5},BYTE_SCALE={bytes:1,kilobytes:1e3,megabytes:1e6,gigabytes:1e9,terabytes:1e12,petabytes:1e15},COMPACT_NUMBER_FORMATTER=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short"}),TWO_FRACTION_NUMBER_FORMATTER=new Intl.NumberFormat("en-US",{maximumFractionDigits:2}),TWO_SIGNIFICANT_NUMBER_FORMATTER=new Intl.NumberFormat("en-US",{minimumSignificantDigits:2,maximumSignificantDigits:2,maximumFractionDigits:2}),PERCENTAGE_FORMATTER=new Intl.NumberFormat("en-US",{style:"unit",unit:"percent",unitDisplay:"narrow",maximumFractionDigits:1}),USD_FORMATTER=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}),BLOCKS=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],MISSING_CHAR="\xB7";function isAggregationWithDimension(aggregation){let[,dimension]=aggregation.split("/");return!!dimension}function getAggregationName(aggregation){return aggregation?.split("/")[0]}function toGroupKey(groupValues){return groupValues.length===0?"":groupValues.join(GROUP_KEY_DELIMITER)}function pad2(n){return String(n).padStart(2,"0")}function pad4(n){return String(n).padStart(4,"0")}function formatHumanMinute(date){return`${pad4(date.getUTCFullYear())}-${pad2(date.getUTCMonth()+1)}-${pad2(date.getUTCDate())} ${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`}function formatPeriodBound(input,showSeconds){let date=new Date(input);if(isNaN(date.getTime()))return input;let minute=formatHumanMinute(date);if(!showSeconds)return minute;let milliseconds=date.getUTCMilliseconds();return`${minute}:${pad2(date.getUTCSeconds())}${milliseconds?`.${String(milliseconds).padStart(3,"0")}`:""}`}function formatPeriodSpan(startInput,endInput){let start=Date.parse(startInput),durationMs=Date.parse(endInput)-start;return!Number.isFinite(durationMs)||durationMs<=0?null:elapsed(durationMs)}function getStatColumns(aggregation){return aggregation==="sum"||aggregation==="count"?["total","avg","min","max"]:["avg","min","max"]}function toNumericValue(value){if(value==null)return null;if(typeof value=="number")return Number.isFinite(value)?value:null;let parsed=Number(value);return Number.isFinite(parsed)?parsed:null}function isNonNullNumber(value){return value!==null}function isPointWithValue(point){return point.value!==null}function getOrCreate(map,key,make){let existing=map.get(key);if(existing!==void 0)return existing;let created=make();return map.set(key,created),created}function getGroupFieldValue(row,field){let value=row[field];return value==null||value===""?"(not set)":String(value)}function normalizeTimestampToIso(timestamp){let parsed=Date.parse(timestamp);return isNaN(parsed)?null:new Date(parsed).toISOString()}function formatStatCell(column,stats,periodStart,periodEnd,formatValue){switch(column){case"total":return formatValue(stats.total);case"avg":return formatValue(stats.avg,{preserveFractionalCount:!0});case"min":{let ts=formatMinMaxTimestamp(new Date(stats.min.timestamp),periodStart,periodEnd);return`${formatValue(stats.min.value)} at ${ts}`}case"max":{let ts=formatMinMaxTimestamp(new Date(stats.max.timestamp),periodStart,periodEnd);return`${formatValue(stats.max.value)} at ${ts}`}}}function buildExpectedTimestamps(periodStart,periodEnd,granularityMs){let start=Date.parse(periodStart),end=Date.parse(periodEnd);if(isNaN(start)||isNaN(end)||granularityMs<=0||end<=start)return[];let timestamps=[];for(let current=start;current<end;current+=granularityMs)timestamps.push(new Date(current).toISOString());return timestamps}function buildObservedTimestamps(observedTimestamps,granularityMs){let timestamps=[...observedTimestamps].map(timestamp=>Date.parse(timestamp)).filter(Number.isFinite).sort((a,b)=>a-b);if(timestamps.length===0||granularityMs<=0)return[];let start=timestamps[0],end=timestamps[timestamps.length-1]+granularityMs;return buildExpectedTimestamps(new Date(start).toISOString(),new Date(end).toISOString(),granularityMs)}function buildSeriesTimestamps(periodStart,periodEnd,granularityMs,observedTimestamps){let expectedTimestamps=buildExpectedTimestamps(periodStart,periodEnd,granularityMs);return observedTimestamps.size===0||expectedTimestamps.some(timestamp=>observedTimestamps.has(timestamp))?expectedTimestamps:buildObservedTimestamps(observedTimestamps,granularityMs)}function formatCount(n){return Math.round(n).toLocaleString("en-US")}function formatDecimal(n){if(!Number.isFinite(n))return String(n);if(n===0||Object.is(n,-0))return"0";let sign=n<0?"-":"",abs=Math.abs(n);if(abs>=1)return`${sign}${abs.toFixed(1)}`;let exponent=Math.floor(Math.log10(abs)),decimals=Math.min(20,Math.max(2,-exponent+1)),trimmed=abs.toFixed(decimals).replace(/(\.\d*?[1-9])0+$/,"$1").replace(/\.0+$/,"").replace(/\.$/,"");return`${sign}${trimmed}`}function formatDuration(durationMs){let durationSeconds=durationMs/1e3;return durationMs<1e3?`${durationMs.toFixed(0)}ms`:durationMs<5e3?`${Math.round(durationSeconds*100)/100}s`:durationSeconds<60?`${durationSeconds.toFixed(0)}s`:durationSeconds<3600?`${(durationSeconds/60).toFixed(0)}m`:`${(durationSeconds/3600).toFixed(0)}h`}function formatBytes(bytes){if(bytes===0)return"0 Bytes";let units=["Bytes","KB","MB","GB","TB","PB"],absoluteBytes=Math.abs(bytes),unitIndex=Math.min(units.length-1,Math.max(0,Math.floor(Math.log(absoluteBytes)/Math.log(1e3)))),value=bytes/1e3**unitIndex;return(unitIndex===1||unitIndex===2)&&(value=Math.round(value),Math.abs(value)===1e3&&unitIndex<units.length-1&&(value/=1e3,unitIndex+=1)),`${TWO_FRACTION_NUMBER_FORMATTER.format(value)} ${units[unitIndex]}`}function formatMetricValue(value,baseUnit,aggregation,opts){let formatCountValue=()=>opts?.preserveFractionalCount&&!Number.isInteger(value)?formatDecimal(value):formatCount(value);if(isAggregationWithDimension(aggregation)||aggregation==="count")return formatCountValue();let unit=normalizeMetricUnit(baseUnit??"units");if(aggregation==="percent"||unit==="percent")return PERCENTAGE_FORMATTER.format(value);if(aggregation==="unique")return COMPACT_NUMBER_FORMATTER.format(value);let withRateSuffix=formatted2=>aggregation==="persecond"?`${formatted2}/s`:formatted2;if(unit==="milliseconds")return withRateSuffix(formatDuration(value));let durationScale=DURATION_SCALE_MS[unit];if(durationScale)return withRateSuffix(formatDuration(value*durationScale));if(unit==="nanoseconds"||unit==="microseconds"){let suffix=unit==="nanoseconds"?" ns":" \xB5s",formatted2=TWO_FRACTION_NUMBER_FORMATTER.format(value);return withRateSuffix(`${formatted2}${suffix}`)}let byteScale=BYTE_SCALE[unit];if(byteScale)return withRateSuffix(formatBytes(value*byteScale));if(unit==="gigabyte hour"||unit==="gigabyte hours"){let formatted2=TWO_SIGNIFICANT_NUMBER_FORMATTER.format(value);return withRateSuffix(`${formatted2} GB-hrs`)}if(unit==="usd"||unit==="us dollars"||unit==="dollars")return withRateSuffix(USD_FORMATTER.format(value));if(unit==="count"&&aggregation==="sum")return formatCountValue();let formatted=COMPACT_NUMBER_FORMATTER.format(value),unitLabel=baseUnit?.trim();return withRateSuffix(!unitLabel||unit==="units"||unit==="count"||unit==="ratio"?formatted:`${formatted} ${unitLabel}`)}function formatMinMaxTimestamp(date,periodStart,periodEnd){return periodStart.getUTCFullYear()===periodEnd.getUTCFullYear()&&periodStart.getUTCMonth()===periodEnd.getUTCMonth()&&periodStart.getUTCDate()===periodEnd.getUTCDate()?`${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`:periodStart.getUTCFullYear()===periodEnd.getUTCFullYear()?`${pad2(date.getUTCMonth()+1)}-${pad2(date.getUTCDate())} ${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`:`${pad4(date.getUTCFullYear())}-${pad2(date.getUTCMonth()+1)}-${pad2(date.getUTCDate())} ${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`}function extractGroupedSeries(data,groupBy,rollupColumn,periodStart,periodEnd,granularityMs){let groups=[],groupValues=new Map,valueByGroup=new Map,observedTimestamps=new Set;for(let row of data){let values=groupBy.map(field=>getGroupFieldValue(row,field)),key=toGroupKey(values);groupValues.has(key)||(groups.push(key),groupValues.set(key,values));let groupMap=getOrCreate(valueByGroup,key,()=>new Map),rawTimestamp=row.timestamp;if(rawTimestamp.length===0)continue;let timestamp=normalizeTimestampToIso(rawTimestamp);if(!timestamp)continue;observedTimestamps.add(timestamp);let numeric=toNumericValue(row[rollupColumn]);groupMap.set(timestamp,numeric)}let expectedTimestamps=buildSeriesTimestamps(periodStart,periodEnd,granularityMs,observedTimestamps),series=new Map;for(let key of groups){let byTimestamp=valueByGroup.get(key);if(!byTimestamp)continue;let points=expectedTimestamps.map(timestamp=>({timestamp,value:byTimestamp.has(timestamp)?byTimestamp.get(timestamp)??null:null}));series.set(key,points)}return{groups,series,groupValues}}function computeGroupStats(points){let present=points.filter(isPointWithValue);if(present.length===0)return{total:0,avg:0,min:{value:0,timestamp:""},max:{value:0,timestamp:""},count:0,allMissing:!0};let total=0,min=present[0],max=present[0];for(let point of present)total+=point.value,point.value<min.value&&(min=point),point.value>max.value&&(max=point);return{total,avg:total/present.length,min:{value:min.value,timestamp:min.timestamp},max:{value:max.value,timestamp:max.timestamp},count:present.length,allMissing:!1}}var MAX_GROUP_VALUE_LENGTH=60;function downsample(values,maxLen){if(maxLen<=0)return[];if(values.length<=maxLen)return[...values];let result=[];for(let i=0;i<maxLen;i++){let start=Math.floor(i*values.length/maxLen),end=Math.floor((i+1)*values.length/maxLen),bucket=values.slice(start,Math.max(start+1,end)),nullCount=bucket.filter(value=>value===null).length;if(nullCount===bucket.length||nullCount>bucket.length/2){result.push(null);continue}let present=bucket.filter(isNonNullNumber),avg=present.reduce((sum,value)=>sum+value,0)/present.length;result.push(avg)}return result}function generateSparkline(values,options={}){let sampled=downsample(values,options.maxLength??MAX_SPARKLINE_LENGTH);if(sampled.length===0)return"";let present=sampled.filter(isNonNullNumber);if(present.length===0)return sampled.map(()=>MISSING_CHAR).join("");let min=options.scale?.min??Math.min(...present),max=options.scale?.max??Math.max(...present);if(min===max){let block=min===0?BLOCKS[0]:BLOCKS[BLOCKS.length-1];return sampled.map(value=>value===null?MISSING_CHAR:block).join("")}let range=max-min;return sampled.map(value=>{if(value===null)return MISSING_CHAR;let ratio=(value-min)/range,index=Math.max(0,Math.min(BLOCKS.length-1,Math.round(ratio*(BLOCKS.length-1))));return BLOCKS[index]}).join("")}function formatMetadataHeader(opts){let showSeconds=opts.intervalSeconds!==void 0&&opts.intervalSeconds<60||[opts.periodStart,opts.periodEnd].some(input=>{let date=new Date(input);return!isNaN(date.getTime())&&(date.getUTCSeconds()!==0||date.getUTCMilliseconds()!==0)}),periodSpan=opts.compact?formatPeriodSpan(opts.periodStart,opts.periodEnd):null,rows=[];!opts.compact&&opts.metric&&opts.aggregation&&rows.push({key:"Metric",value:`${opts.metric} ${opts.aggregation}`}),!opts.compact&&opts.definitions&&rows.push(...opts.definitions),rows.push({key:"Period",value:`${formatPeriodBound(opts.periodStart,showSeconds)} to ${formatPeriodBound(opts.periodEnd,showSeconds)} (UTC)${periodSpan?` ${periodSpan}`:""}`}),opts.granularity?rows.push({key:"Interval",value:"days"in opts.granularity?`${formatGranularity(opts.granularity)} (${opts.bucketTimezone??"UTC"})`:formatGranularity(opts.granularity)}):opts.intervalSeconds&&rows.push({key:"Interval",value:`${opts.intervalSeconds}s`}),typeof opts.periodUnique=="number"&&rows.push({key:getAggregationName(opts.aggregation)==="singleton"?"Singleton (period)":"Unique (period)",value:formatCount(opts.periodUnique)}),!opts.compact&&opts.filter&&rows.push({key:"Filter",value:opts.filter}),!opts.compact&&opts.orderBy&&opts.orderDirection&&rows.push({key:"Order By",value:`${opts.orderBy} ${opts.orderDirection}${opts.orderBy==="count"?" (default)":""}`});let teamLabel=opts.teamName??opts.scope.ownerId;if(opts.scope.type==="project")rows.push({key:"Project",value:`${opts.projectName??opts.scope.projectIds[0]} (${teamLabel})`});else if(opts.projects&&opts.projects.length>0){let shown=opts.projects.slice(0,MAX_HEADER_PROJECTS),more=opts.projects.length-shown.length;rows.push({key:"Projects",value:`${shown.join(", ")}${more>0?` and ${more} more`:""} (${teamLabel})`})}else rows.push({key:"Team",value:`${teamLabel} (all projects)`});return!opts.compact&&typeof opts.groupCount=="number"&&rows.push({key:"Groups",value:String(opts.groupCount)}),rows.map(row=>`> ${import_chalk.default.gray(`${row.key}:`)} ${row.value}`).join(`
7
+ import{getResolvedOrderMetadata,getRollupColumnName}from"./chunk-C335SWOB.js";import{formatGranularity}from"./chunk-IVSSTHB6.js";import{ellipsizeMiddle}from"./chunk-TOTTVS5P.js";import{elapsed}from"./chunk-Q7D7RGXM.js";import{indent_default}from"./chunk-GZNDA6SV.js";import{table}from"./chunk-CJZE7647.js";import{require_ms}from"./chunk-MXTC4ZAQ.js";import{remoteText}from"./chunk-GLIQ4KNY.js";import{require_source}from"./chunk-NB2WLB3J.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_ms=__toESM(require_ms(),1),MINUTE_MS=60*1e3,HOUR_MS=60*MINUTE_MS,DAY_MS=24*HOUR_MS;function toGranularityDuration(input){let milliseconds=(0,import_ms.default)(input);if(milliseconds===void 0)throw new Error(`Invalid granularity format "${input}". Use 1m, 5m, 15m, 1h, 4h, 1d.`);return milliseconds>=DAY_MS?{days:milliseconds/DAY_MS}:milliseconds>=HOUR_MS?{hours:milliseconds/HOUR_MS}:{minutes:milliseconds/MINUTE_MS}}function toGranularityMs(input){let milliseconds=(0,import_ms.default)(input);if(milliseconds===void 0)throw new Error(`Invalid granularity format "${input}".`);return milliseconds}var GRANULARITY_THRESHOLDS=[[1*HOUR_MS,"1m","1m"],[2*HOUR_MS,"5m","5m"],[12*HOUR_MS,"15m","5m"],[3*DAY_MS,"1h","1h"],[30*DAY_MS,"4h","4h"]],FALLBACK_GRANULARITY="1d";function getAutoGranularity(rangeMs){for(let[maxRange,defaultG]of GRANULARITY_THRESHOLDS)if(rangeMs<=maxRange)return defaultG;return FALLBACK_GRANULARITY}function getMinGranularity(rangeMs){for(let[maxRange,,minG]of GRANULARITY_THRESHOLDS)if(rangeMs<=maxRange)return minG;return FALLBACK_GRANULARITY}function computeGranularity(rangeMs,explicit){if(!explicit){let auto=getAutoGranularity(rangeMs);return{duration:toGranularityDuration(auto),adjusted:!1}}let minG=getMinGranularity(rangeMs),explicitMs=toGranularityMs(explicit),minMs=toGranularityMs(minG);if(explicitMs<minMs){let rangeDays=Math.round(rangeMs/DAY_MS),rangeHours=Math.round(rangeMs/HOUR_MS),rangeLabel=rangeDays>=1?`${rangeDays}-day`:`${rangeHours}-hour`;return{duration:toGranularityDuration(minG),adjusted:!0,notice:`Granularity adjusted from ${explicit} to ${minG} for a ${rangeLabel} time range.`}}return{duration:toGranularityDuration(explicit),adjusted:!1}}function toGranularityMsFromDuration(duration){return"minutes"in duration?duration.minutes*MINUTE_MS:"hours"in duration?duration.hours*HOUR_MS:duration.days*DAY_MS}var CANONICAL_AGGREGATIONS=["count","sum","avg","min","max","p50","p75","p90","p95","p99","stddev"];function isCanonicalAggregation(aggregation){return CANONICAL_AGGREGATIONS.includes(aggregation)}var DURATION_UNITS=new Set(["nanoseconds","microseconds","milliseconds","seconds","minutes","hours","days"]);function normalizeMetricUnit(unit){return unit.trim().toLowerCase().replace(/[_\s]+/g," ")}function getPreferredCustomMetricAggregation(unit){let normalizedUnit=normalizeMetricUnit(unit);return DURATION_UNITS.has(normalizedUnit)?"p75":normalizedUnit==="percent"?"avg":"sum"}function getDefaultCustomMetricAggregation(unit,aggregations){let preferredAggregation=getPreferredCustomMetricAggregation(unit);return aggregations?.includes(preferredAggregation)?preferredAggregation:aggregations?.includes("sum")?"sum":aggregations?.find(isCanonicalAggregation)}var import_chalk=__toESM(require_source(),1);var GROUP_KEY_DELIMITER="",MAX_SPARKLINE_LENGTH=120,MAX_HEADER_PROJECTS=5,DURATION_SCALE_MS={seconds:1e3,minutes:6e4,hours:36e5,days:864e5},BYTE_SCALE={bytes:1,kilobytes:1e3,megabytes:1e6,gigabytes:1e9,terabytes:1e12,petabytes:1e15},COMPACT_NUMBER_FORMATTER=new Intl.NumberFormat("en-US",{notation:"compact",compactDisplay:"short"}),TWO_FRACTION_NUMBER_FORMATTER=new Intl.NumberFormat("en-US",{maximumFractionDigits:2}),TWO_SIGNIFICANT_NUMBER_FORMATTER=new Intl.NumberFormat("en-US",{minimumSignificantDigits:2,maximumSignificantDigits:2,maximumFractionDigits:2}),PERCENTAGE_FORMATTER=new Intl.NumberFormat("en-US",{style:"unit",unit:"percent",unitDisplay:"narrow",maximumFractionDigits:1}),USD_FORMATTER=new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2,maximumFractionDigits:2}),BLOCKS=["\u2581","\u2582","\u2583","\u2584","\u2585","\u2586","\u2587","\u2588"],MISSING_CHAR="\xB7";function isAggregationWithDimension(aggregation){let[,dimension]=aggregation.split("/");return!!dimension}function getAggregationName(aggregation){return aggregation?.split("/")[0]}function toGroupKey(groupValues){return groupValues.length===0?"":groupValues.join(GROUP_KEY_DELIMITER)}function pad2(n){return String(n).padStart(2,"0")}function pad4(n){return String(n).padStart(4,"0")}function formatHumanMinute(date){return`${pad4(date.getUTCFullYear())}-${pad2(date.getUTCMonth()+1)}-${pad2(date.getUTCDate())} ${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`}function formatPeriodBound(input,showSeconds){let date=new Date(input);if(isNaN(date.getTime()))return input;let minute=formatHumanMinute(date);if(!showSeconds)return minute;let milliseconds=date.getUTCMilliseconds();return`${minute}:${pad2(date.getUTCSeconds())}${milliseconds?`.${String(milliseconds).padStart(3,"0")}`:""}`}function formatPeriodSpan(startInput,endInput){let start=Date.parse(startInput),durationMs=Date.parse(endInput)-start;return!Number.isFinite(durationMs)||durationMs<=0?null:elapsed(durationMs)}function getStatColumns(aggregation){return aggregation==="sum"||aggregation==="count"?["total","avg","min","max"]:["avg","min","max"]}function toNumericValue(value){if(value==null)return null;if(typeof value=="number")return Number.isFinite(value)?value:null;let parsed=Number(value);return Number.isFinite(parsed)?parsed:null}function isNonNullNumber(value){return value!==null}function isPointWithValue(point){return point.value!==null}function getOrCreate(map,key,make){let existing=map.get(key);if(existing!==void 0)return existing;let created=make();return map.set(key,created),created}function getGroupFieldValue(row,field){let value=row[field];return value==null||value===""?"(not set)":String(value)}function normalizeTimestampToIso(timestamp){let parsed=Date.parse(timestamp);return isNaN(parsed)?null:new Date(parsed).toISOString()}function formatStatCell(column,stats,periodStart,periodEnd,formatValue){switch(column){case"total":return formatValue(stats.total);case"avg":return formatValue(stats.avg,{preserveFractionalCount:!0});case"min":{let ts=formatMinMaxTimestamp(new Date(stats.min.timestamp),periodStart,periodEnd);return`${formatValue(stats.min.value)} at ${ts}`}case"max":{let ts=formatMinMaxTimestamp(new Date(stats.max.timestamp),periodStart,periodEnd);return`${formatValue(stats.max.value)} at ${ts}`}}}function buildExpectedTimestamps(periodStart,periodEnd,granularityMs){let start=Date.parse(periodStart),end=Date.parse(periodEnd);if(isNaN(start)||isNaN(end)||granularityMs<=0||end<=start)return[];let timestamps=[];for(let current=start;current<end;current+=granularityMs)timestamps.push(new Date(current).toISOString());return timestamps}function buildObservedTimestamps(observedTimestamps,granularityMs){let timestamps=[...observedTimestamps].map(timestamp=>Date.parse(timestamp)).filter(Number.isFinite).sort((a,b)=>a-b);if(timestamps.length===0||granularityMs<=0)return[];let start=timestamps[0],end=timestamps[timestamps.length-1]+granularityMs;return buildExpectedTimestamps(new Date(start).toISOString(),new Date(end).toISOString(),granularityMs)}function buildSeriesTimestamps(periodStart,periodEnd,granularityMs,observedTimestamps){let expectedTimestamps=buildExpectedTimestamps(periodStart,periodEnd,granularityMs);return observedTimestamps.size===0||expectedTimestamps.some(timestamp=>observedTimestamps.has(timestamp))?expectedTimestamps:buildObservedTimestamps(observedTimestamps,granularityMs)}function formatCount(n){return Math.round(n).toLocaleString("en-US")}function formatDecimal(n){if(!Number.isFinite(n))return String(n);if(n===0||Object.is(n,-0))return"0";let sign=n<0?"-":"",abs=Math.abs(n);if(abs>=1)return`${sign}${abs.toFixed(1)}`;let exponent=Math.floor(Math.log10(abs)),decimals=Math.min(20,Math.max(2,-exponent+1)),trimmed=abs.toFixed(decimals).replace(/(\.\d*?[1-9])0+$/,"$1").replace(/\.0+$/,"").replace(/\.$/,"");return`${sign}${trimmed}`}function formatDuration(durationMs){let durationSeconds=durationMs/1e3;return durationMs<1e3?`${durationMs.toFixed(0)}ms`:durationMs<5e3?`${Math.round(durationSeconds*100)/100}s`:durationSeconds<60?`${durationSeconds.toFixed(0)}s`:durationSeconds<3600?`${(durationSeconds/60).toFixed(0)}m`:`${(durationSeconds/3600).toFixed(0)}h`}function formatBytes(bytes){if(bytes===0)return"0 Bytes";let units=["Bytes","KB","MB","GB","TB","PB"],absoluteBytes=Math.abs(bytes),unitIndex=Math.min(units.length-1,Math.max(0,Math.floor(Math.log(absoluteBytes)/Math.log(1e3)))),value=bytes/1e3**unitIndex;return(unitIndex===1||unitIndex===2)&&(value=Math.round(value),Math.abs(value)===1e3&&unitIndex<units.length-1&&(value/=1e3,unitIndex+=1)),`${TWO_FRACTION_NUMBER_FORMATTER.format(value)} ${units[unitIndex]}`}function formatMetricValue(value,baseUnit,aggregation,opts){let formatCountValue=()=>opts?.preserveFractionalCount&&!Number.isInteger(value)?formatDecimal(value):formatCount(value);if(isAggregationWithDimension(aggregation)||aggregation==="count")return formatCountValue();let unit=normalizeMetricUnit(baseUnit??"units");if(aggregation==="percent"||unit==="percent")return PERCENTAGE_FORMATTER.format(value);if(aggregation==="unique")return COMPACT_NUMBER_FORMATTER.format(value);let withRateSuffix=formatted2=>aggregation==="persecond"?`${formatted2}/s`:formatted2;if(unit==="milliseconds")return withRateSuffix(formatDuration(value));let durationScale=DURATION_SCALE_MS[unit];if(durationScale)return withRateSuffix(formatDuration(value*durationScale));if(unit==="nanoseconds"||unit==="microseconds"){let suffix=unit==="nanoseconds"?" ns":" \xB5s",formatted2=TWO_FRACTION_NUMBER_FORMATTER.format(value);return withRateSuffix(`${formatted2}${suffix}`)}let byteScale=BYTE_SCALE[unit];if(byteScale)return withRateSuffix(formatBytes(value*byteScale));if(unit==="gigabyte hour"||unit==="gigabyte hours"){let formatted2=TWO_SIGNIFICANT_NUMBER_FORMATTER.format(value);return withRateSuffix(`${formatted2} GB-hrs`)}if(unit==="usd"||unit==="us dollars"||unit==="dollars")return withRateSuffix(USD_FORMATTER.format(value));if(unit==="count"&&aggregation==="sum")return formatCountValue();let formatted=COMPACT_NUMBER_FORMATTER.format(value),unitLabel=baseUnit?.trim();return withRateSuffix(!unitLabel||unit==="units"||unit==="count"||unit==="ratio"?formatted:`${formatted} ${unitLabel}`)}function formatMinMaxTimestamp(date,periodStart,periodEnd){return periodStart.getUTCFullYear()===periodEnd.getUTCFullYear()&&periodStart.getUTCMonth()===periodEnd.getUTCMonth()&&periodStart.getUTCDate()===periodEnd.getUTCDate()?`${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`:periodStart.getUTCFullYear()===periodEnd.getUTCFullYear()?`${pad2(date.getUTCMonth()+1)}-${pad2(date.getUTCDate())} ${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`:`${pad4(date.getUTCFullYear())}-${pad2(date.getUTCMonth()+1)}-${pad2(date.getUTCDate())} ${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`}function extractGroupedSeries(data,groupBy,rollupColumn,periodStart,periodEnd,granularityMs){let groups=[],groupValues=new Map,valueByGroup=new Map,observedTimestamps=new Set;for(let row of data){let values=groupBy.map(field=>getGroupFieldValue(row,field)),key=toGroupKey(values);groupValues.has(key)||(groups.push(key),groupValues.set(key,values));let groupMap=getOrCreate(valueByGroup,key,()=>new Map),rawTimestamp=row.timestamp;if(rawTimestamp.length===0)continue;let timestamp=normalizeTimestampToIso(rawTimestamp);if(!timestamp)continue;observedTimestamps.add(timestamp);let numeric=toNumericValue(row[rollupColumn]);groupMap.set(timestamp,numeric)}let expectedTimestamps=buildSeriesTimestamps(periodStart,periodEnd,granularityMs,observedTimestamps),series=new Map;for(let key of groups){let byTimestamp=valueByGroup.get(key);if(!byTimestamp)continue;let points=expectedTimestamps.map(timestamp=>({timestamp,value:byTimestamp.has(timestamp)?byTimestamp.get(timestamp)??null:null}));series.set(key,points)}return{groups,series,groupValues}}function computeGroupStats(points){let present=points.filter(isPointWithValue);if(present.length===0)return{total:0,avg:0,min:{value:0,timestamp:""},max:{value:0,timestamp:""},count:0,allMissing:!0};let total=0,min=present[0],max=present[0];for(let point of present)total+=point.value,point.value<min.value&&(min=point),point.value>max.value&&(max=point);return{total,avg:total/present.length,min:{value:min.value,timestamp:min.timestamp},max:{value:max.value,timestamp:max.timestamp},count:present.length,allMissing:!1}}var MAX_GROUP_VALUE_LENGTH=60;function downsample(values,maxLen){if(maxLen<=0)return[];if(values.length<=maxLen)return[...values];let result=[];for(let i=0;i<maxLen;i++){let start=Math.floor(i*values.length/maxLen),end=Math.floor((i+1)*values.length/maxLen),bucket=values.slice(start,Math.max(start+1,end)),nullCount=bucket.filter(value=>value===null).length;if(nullCount===bucket.length||nullCount>bucket.length/2){result.push(null);continue}let present=bucket.filter(isNonNullNumber),avg=present.reduce((sum,value)=>sum+value,0)/present.length;result.push(avg)}return result}function generateSparkline(values,options={}){let sampled=downsample(values,options.maxLength??MAX_SPARKLINE_LENGTH);if(sampled.length===0)return"";let present=sampled.filter(isNonNullNumber);if(present.length===0)return sampled.map(()=>MISSING_CHAR).join("");let min=options.scale?.min??Math.min(...present),max=options.scale?.max??Math.max(...present);if(min===max){let block=min===0?BLOCKS[0]:BLOCKS[BLOCKS.length-1];return sampled.map(value=>value===null?MISSING_CHAR:block).join("")}let range=max-min;return sampled.map(value=>{if(value===null)return MISSING_CHAR;let ratio=(value-min)/range,index=Math.max(0,Math.min(BLOCKS.length-1,Math.round(ratio*(BLOCKS.length-1))));return BLOCKS[index]}).join("")}function formatMetadataHeader(opts){let showSeconds=opts.intervalSeconds!==void 0&&opts.intervalSeconds<60||[opts.periodStart,opts.periodEnd].some(input=>{let date=new Date(input);return!isNaN(date.getTime())&&(date.getUTCSeconds()!==0||date.getUTCMilliseconds()!==0)}),periodSpan=opts.compact?formatPeriodSpan(opts.periodStart,opts.periodEnd):null,rows=[];!opts.compact&&opts.metric&&opts.aggregation&&rows.push({key:"Metric",value:`${opts.metric} ${opts.aggregation}`}),!opts.compact&&opts.definitions&&rows.push(...opts.definitions),rows.push({key:"Period",value:`${formatPeriodBound(opts.periodStart,showSeconds)} to ${formatPeriodBound(opts.periodEnd,showSeconds)} (UTC)${periodSpan?` ${periodSpan}`:""}`}),opts.granularity?rows.push({key:"Interval",value:"days"in opts.granularity?`${formatGranularity(opts.granularity)} (${opts.bucketTimezone??"UTC"})`:formatGranularity(opts.granularity)}):opts.intervalSeconds&&rows.push({key:"Interval",value:`${opts.intervalSeconds}s`}),typeof opts.periodUnique=="number"&&rows.push({key:getAggregationName(opts.aggregation)==="singleton"?"Singleton (period)":"Unique (period)",value:formatCount(opts.periodUnique)}),!opts.compact&&opts.filter&&rows.push({key:"Filter",value:opts.filter}),!opts.compact&&opts.orderBy&&opts.orderDirection&&rows.push({key:"Order By",value:`${opts.orderBy} ${opts.orderDirection}${opts.orderBy==="count"?" (default)":""}`});let teamLabel=opts.teamName??opts.scope.ownerId;if(opts.scope.type==="project")rows.push({key:"Project",value:`${opts.projectName??opts.scope.projectIds[0]} (${teamLabel})`});else if(opts.projects&&opts.projects.length>0){let shown=opts.projects.slice(0,MAX_HEADER_PROJECTS),more=opts.projects.length-shown.length;rows.push({key:"Projects",value:`${shown.join(", ")}${more>0?` and ${more} more`:""} (${teamLabel})`})}else rows.push({key:"Team",value:`${teamLabel} (all projects)`});return!opts.compact&&typeof opts.groupCount=="number"&&rows.push({key:"Groups",value:String(opts.groupCount)}),rows.map(row=>`> ${import_chalk.default.gray(`${row.key}:`)} ${row.value}`).join(`
8
8
  `)}function formatSummaryTable(opts){let statColumns=getStatColumns(opts.aggregation),header=[...opts.groupByFields,...statColumns],rows=[header.map(name=>import_chalk.default.bold(import_chalk.default.cyan(name)))];for(let row of opts.rows){let nextRow=row.groupValues.map(v=>ellipsizeMiddle(v,MAX_GROUP_VALUE_LENGTH,opts.ansiAwareGroupValues));if(row.stats.allMissing){nextRow.push(...statColumns.map(()=>"--")),rows.push(nextRow);continue}nextRow.push(...statColumns.map(column=>formatStatCell(column,row.stats,opts.periodStart,opts.periodEnd,opts.formatValue))),rows.push(nextRow)}let centeredColumns=new Set(["min","max"]),align=header.map(col=>centeredColumns.has(col)?"c":"r");return indent_default(table(rows,{align,hsep:2}),2)}function formatSparklineSection(groupRows,sparklines,groupByFields,compact=!1){if(groupRows.length===0){let sparkline=sparklines[0],chart2=sparkline?indent_default(sparkline,2):"";return compact?chart2:["sparklines:",chart2].filter(Boolean).join(`
9
9
  `)}let rows=[[...groupByFields,compact?"":"sparkline"].map(name=>import_chalk.default.bold(import_chalk.default.cyan(name))),...groupRows.map((groupValues,index)=>[...groupValues.map(v=>ellipsizeMiddle(v,MAX_GROUP_VALUE_LENGTH,compact)),sparklines[index]??""])],align=groupByFields.map(()=>"r");align.push("l");let chart=indent_default(table(rows,{align,hsep:2}),2);return compact?chart:`sparklines:
10
10
  ${chart}`}function formatText(response,opts){let rollupColumn=getRollupColumnName(opts.metric,opts.aggregation),formatValue=(value,formatOptions)=>formatMetricValue(value,opts.metricUnit,opts.aggregation,formatOptions),granularityMs=toGranularityMsFromDuration(opts.granularity),orderMetadata=getResolvedOrderMetadata(opts,response),{groups,series,groupValues}=extractGroupedSeries(response.data??[],opts.groupBy,rollupColumn,opts.periodStart,opts.periodEnd,granularityMs),periodUnique;if(isAggregationWithDimension(opts.aggregation)&&opts.groupBy.length===0){let summaryValue=toNumericValue(response.summary?.[0]?.[rollupColumn]);summaryValue!==null&&(periodUnique=summaryValue)}let metadata=formatMetadataHeader({metric:opts.metric,aggregation:opts.aggregation,periodStart:opts.periodStart,periodEnd:opts.periodEnd,granularity:opts.granularity,periodUnique,bucketTimezone:opts.bucketTimezone,filter:opts.filter,...opts.groupBy.length>0?orderMetadata:{},scope:opts.scope,projectName:opts.projectName,teamName:opts.teamName,groupCount:opts.groupBy.length>0?groups.length:void 0,compact:opts.presentation?.compact});if(groups.length===0)return`${metadata}
@@ -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{emitAlertsScopeError,resolveAlertsScope}from"./chunk-TBWFT22U.js";import{handleValidationError,validateAllProjectMutualExclusivity}from"./chunk-ZJNDLFZ7.js";import{getScope}from"./chunk-YFMEZ4SZ.js";import{AGENT_REASON,buildCommandWithGlobalFlags,outputAgentError}from"./chunk-M2GHHK7B.js";import{getProjectByNameOrId}from"./chunk-DJZBJC2A.js";import{ProjectNotFound,isAPIError}from"./chunk-GOI2VVI7.js";async function resolveRulesTeam(client,jsonOutput){let scope;try{scope=await getScope(client,{resolveLocalScope:!0})}catch(err){if(isAPIError(err)&&(err.status===403||err.status===404))return emitAlertsScopeError(client,jsonOutput,err.code||"API_ERROR",err.serverMessage||`API error (${err.status}).`,{reason:AGENT_REASON.MISSING_SCOPE,hint:"The selected team could not be loaded. Select a team you can access, or pass --scope <team-slug>.",next:[{command:buildCommandWithGlobalFlags(client.argv,"teams switch"),when:"Select a team"},{command:buildCommandWithGlobalFlags(client.argv,"whoami"),when:"Inspect the current scope"}]});throw err}let{team}=scope;return team?{teamId:team.id}:emitAlertsScopeError(client,jsonOutput,"NO_TEAM","No team context found. Run `vercel switch` to select a team, use `--scope <team>`, or link a team project.",{reason:AGENT_REASON.MISSING_SCOPE,hint:"Monitors belong to a team. Select the team before retrying.",next:[{command:buildCommandWithGlobalFlags(client.argv,"teams switch"),when:"Select a team"},{command:buildCommandWithGlobalFlags(client.argv,"whoami"),when:"Inspect the current scope"}]})}async function resolveRulesProject(client,projectNameOrId,jsonOutput,command){let teamScope=await resolveRulesTeam(client,jsonOutput);if(typeof teamScope=="number")return teamScope;try{let project=await getProjectByNameOrId(client,projectNameOrId,teamScope.teamId);return project instanceof ProjectNotFound?emitAlertsScopeError(client,jsonOutput,"PROJECT_NOT_FOUND",`Project "${projectNameOrId}" was not found in the selected team.`,{reason:AGENT_REASON.NOT_FOUND,next:[{command:buildCommandWithGlobalFlags(client.argv,`${command} --project <name_or_id>`),when:"Retry with a valid project"}]}):{...teamScope,projectId:project.id,projectName:project.name}}catch(error){if(!isAPIError(error))throw error;return emitAlertsScopeError(client,jsonOutput,error.code||"API_ERROR",error.serverMessage||`API error (${error.status}).`,{reason:error.status===401?"not_authorized":error.status===403?"forbidden":AGENT_REASON.API_ERROR})}}async function parseRulesFlagsAndScope(client,flags,jsonOutput,command="monitors ls"){let mutual=validateAllProjectMutualExclusivity(flags["--all"],flags["--project"]);if(!mutual.valid)return outputAgentError(client,{status:"error",reason:AGENT_REASON.INVALID_ARGUMENTS,message:mutual.message,next:[{command:buildCommandWithGlobalFlags(client.argv,"monitors --help"),when:"Use either `--project` or `--all`, not both"}]},2),handleValidationError(mutual,jsonOutput,client);if(flags["--all"])return resolveRulesTeam(client,jsonOutput);if(flags["--project"])return resolveRulesProject(client,flags["--project"],jsonOutput,command);let linkedScope=await resolveAlertsScope(client,{jsonOutput,command});if(typeof linkedScope=="number")return linkedScope;let teamScope=await resolveRulesTeam(client,jsonOutput);return typeof teamScope=="number"?teamScope:linkedScope.teamId===teamScope.teamId?linkedScope:teamScope}export{resolveRulesTeam,resolveRulesProject,parseRulesFlagsAndScope};
7
+ import{emitAlertsScopeError,resolveAlertsScope}from"./chunk-CSCUVSJM.js";import{handleValidationError,validateAllProjectMutualExclusivity}from"./chunk-ZJNDLFZ7.js";import{getScope}from"./chunk-NLK7NGVP.js";import{getProjectByNameOrId}from"./chunk-DJZBJC2A.js";import{AGENT_REASON,buildCommandWithGlobalFlags,outputAgentError}from"./chunk-4SS6W6JK.js";import{ProjectNotFound,isAPIError}from"./chunk-GOI2VVI7.js";async function resolveRulesTeam(client,jsonOutput){let scope;try{scope=await getScope(client,{resolveLocalScope:!0})}catch(err){if(isAPIError(err)&&(err.status===403||err.status===404))return emitAlertsScopeError(client,jsonOutput,err.code||"API_ERROR",err.serverMessage||`API error (${err.status}).`,{reason:AGENT_REASON.MISSING_SCOPE,hint:"The selected team could not be loaded. Select a team you can access, or pass --scope <team-slug>.",next:[{command:buildCommandWithGlobalFlags(client.argv,"teams switch"),when:"Select a team"},{command:buildCommandWithGlobalFlags(client.argv,"whoami"),when:"Inspect the current scope"}]});throw err}let{team}=scope;return team?{teamId:team.id}:emitAlertsScopeError(client,jsonOutput,"NO_TEAM","No team context found. Run `vercel switch` to select a team, use `--scope <team>`, or link a team project.",{reason:AGENT_REASON.MISSING_SCOPE,hint:"Monitors belong to a team. Select the team before retrying.",next:[{command:buildCommandWithGlobalFlags(client.argv,"teams switch"),when:"Select a team"},{command:buildCommandWithGlobalFlags(client.argv,"whoami"),when:"Inspect the current scope"}]})}async function resolveRulesProject(client,projectNameOrId,jsonOutput,command){let teamScope=await resolveRulesTeam(client,jsonOutput);if(typeof teamScope=="number")return teamScope;try{let project=await getProjectByNameOrId(client,projectNameOrId,teamScope.teamId);return project instanceof ProjectNotFound?emitAlertsScopeError(client,jsonOutput,"PROJECT_NOT_FOUND",`Project "${projectNameOrId}" was not found in the selected team.`,{reason:AGENT_REASON.NOT_FOUND,next:[{command:buildCommandWithGlobalFlags(client.argv,`${command} --project <name_or_id>`),when:"Retry with a valid project"}]}):{...teamScope,projectId:project.id,projectName:project.name}}catch(error){if(!isAPIError(error))throw error;return emitAlertsScopeError(client,jsonOutput,error.code||"API_ERROR",error.serverMessage||`API error (${error.status}).`,{reason:error.status===401?"not_authorized":error.status===403?"forbidden":AGENT_REASON.API_ERROR})}}async function parseRulesFlagsAndScope(client,flags,jsonOutput,command="monitors ls"){let mutual=validateAllProjectMutualExclusivity(flags["--all"],flags["--project"]);if(!mutual.valid)return outputAgentError(client,{status:"error",reason:AGENT_REASON.INVALID_ARGUMENTS,message:mutual.message,next:[{command:buildCommandWithGlobalFlags(client.argv,"monitors --help"),when:"Use either `--project` or `--all`, not both"}]},2),handleValidationError(mutual,jsonOutput,client);if(flags["--all"])return resolveRulesTeam(client,jsonOutput);if(flags["--project"])return resolveRulesProject(client,flags["--project"],jsonOutput,command);let linkedScope=await resolveAlertsScope(client,{jsonOutput,command});if(typeof linkedScope=="number")return linkedScope;let teamScope=await resolveRulesTeam(client,jsonOutput);return typeof teamScope=="number"?teamScope:linkedScope.teamId===teamScope.teamId?linkedScope:teamScope}export{resolveRulesTeam,resolveRulesProject,parseRulesFlagsAndScope};
@@ -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{markOnboardingSeen}from"./chunk-22XQ3FQJ.js";import{isInteractiveHumanRun}from"./chunk-SZO73QV5.js";import{isGuidanceEnabled}from"./chunk-TAAWMNNL.js";import{require_open}from"./chunk-PVASGBEF.js";import{getTeams}from"./chunk-Y2FVJ7YO.js";import{printError}from"./chunk-TPMBWSAM.js";import{TelemetryClient}from"./chunk-KDCODXVL.js";import{createDpopKey,deleteDpopKey,deviceAccessTokenRequest,deviceAuthorizationRequest,getCachedUsername,getUser,humanizePath,isDpopLoginEnabled,isOAuthError,processDeviceAuthorizationResponse,processTokenResponse}from"./chunk-IBZJP22D.js";import{parseArguments}from"./chunk-LYL26S3N.js";import{getTeamByIdOrSlug}from"./chunk-2VBFQZ72.js";import{getCommandName}from"./chunk-B4KA3ZH2.js";import{SPINNER,countRows,output_manager_default}from"./chunk-AP6DZGTK.js";import{require_dist}from"./chunk-MCYG7CCE.js";import{require_ansi_escapes}from"./chunk-YHPPP3SF.js";import{require_source}from"./chunk-NB2WLB3J.js";import{require_strip_ansi}from"./chunk-BULSRTQE.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_chalk3=__toESM(require_source(),1),import_error_utils=__toESM(require_dist(),1),open=__toESM(require_open(),1),import_ansi_escapes=__toESM(require_ansi_escapes(),1);import readline from"node:readline";import{KNOWN_AGENTS}from"@vercel/detect-agent";async function updateCurrentTeamAfterLogin(client,ssoTeamId){if(ssoTeamId)client.updateConfig({currentTeam:ssoTeamId});else{let user=null;try{user=await getUser(client)}catch{return output_manager_default.error("Failed to fetch the logged in user. Please try again."),1}client.updateConfig({currentTeam:user.version==="northstar"&&user.defaultTeamId?user.defaultTeamId:void 0})}}var LoginTelemetryClient=class extends TelemetryClient{trackState(...args){this.trackLoginState(...args)}trackDpopKey(storage){this.trackDpopKeyStorage(storage)}};import{performance}from"node:perf_hooks";var{waitingFrame,settledFrame,entrance,period,finishFrame,finishDuration}=(()=>{let TURN=Math.PI*2.5,SPIN2=2,BIRTH=.02,LAG=.045,GROW=.34,PEAK=TURN*2.4/SPIN2,SETTLE=.5,DRAG=3,REACH=24,LABEL_AT=1.95,TYPE=.045,FADE=.1,T0=1.56,DWELL=.8,CLIMB=.12,PUSH=.7,LATE=.5,GLOW=.3,SHEEN=.85,LEN=Math.hypot(.507,.862),LX=-.507/LEN,LZ=-.862/LEN,LIT=-LZ,S=Math.SQRT1_2,NORMALS=[[0,-1],[S,-S],[1,0],[S,S],[0,1],[-S,S],[-1,0],[-S,-S]],entrance2=2.4,period2=7,clamp2=(n,lo=0,hi=1)=>Math.min(hi,Math.max(lo,n)),smooth=n=>n*n*(3-2*n),easeOut=n=>1-(1-n)**3,lerp=(a,b,s)=>a*(1-s)+b*s,toneOf=n=>Math.max(0,Math.min(255,Math.round(n))),bit=(u,r)=>{let h=Math.imul(u,374761393)^Math.imul(r+11,668265263);return h=Math.imul(h^h>>>13,1274126177),h>>>15&1?"1":"0"},checkTime=time=>{if(typeof time!="number"||!Number.isFinite(time)||time<0)throw new RangeError("time must be a finite number of seconds >= 0")},checkLayout=(width,alignment)=>{if(width!==30&&width!==60)throw new RangeError("width must be 30 or 60");if(alignment!=="left"&&alignment!=="center")throw new RangeError("alignment must be left or center")};function rowAt(t,r){let tau=t-BIRTH-(7-r)*LAG,q=1-clamp2(tau/SPIN2),E=TURN*(8*q**3-3*q**4)/5,vE=tau>0&&tau<SPIN2?-TURN*(24*q*q-12*q**3)/(5*SPIN2):0,phi=(t-T0-(8-1-r)*CLIMB)/period2,f=phi-Math.floor(phi),w=2*Math.PI*f,turn=(1-Math.cos(w))/2,g=easeOut(clamp2(tau/GROW)),settle=1-smooth(clamp2((tau-SPIN2+SETTLE)/SETTLE));return{th:E-Math.PI*f+DWELL/2*Math.sin(w),v:vE-Math.PI/period2*(1-DWELL*Math.cos(w)),g,e:g*Math.min(1,Math.abs(vE)/PEAK+GLOW*turn),live:settle+(1-settle)*SHEEN*turn,drag:E-PUSH*(1-Math.cos(w-LATE))/2,reach:tau/.45}}let restRow=()=>({th:0,v:0,g:1,e:0,live:0,drag:0,reach:9});function labelAt(t){let mix=[];for(let i=0;i<6;i++){let start=LABEL_AT+i*TYPE;mix.push(t<start?0:smooth(clamp2((t-start)/FADE)))}return{mix,keep:t<LABEL_AT?1:1-smooth(clamp2((t-LABEL_AT)/FADE))}}function render(rows,mix,keep,width,alignment){let c=alignment==="left"?12:width/2-4,span=Math.max(c,width-c),grid=[];for(let r=0;r<8;r++){let{th,g,e,live,drag,reach}=rows[r],row=[];for(let x=0;x<width;x++){let dx=x+.5-c,nx=dx/span,k=.35+.65/(1+(dx/REACH)**2),vis=smooth(clamp2((reach-Math.abs(nx))/.3)),tone=toneOf((20+30*e*k)*(1-.72*nx*nx)*vis);row.push(tone>=3?[bit(x-Math.round(drag*DRAG*k),r),tone]:[" ",0])}if(g>0){let hw=10.5*(r+.5)/8*g,hd=8/2*g,ch=Math.min(.5*g,hw/2,hd/2),cs=Math.cos(th),sn=Math.sin(th),at=(px,pz)=>c+px*cs+pz*sn,front=244-2.6*r,fade=.5+.5*g,loop=[[-hw+ch,-hd],[hw-ch,-hd],[hw,-hd+ch],[hw,hd-ch],[hw-ch,hd],[-hw+ch,hd],[-hw,hd-ch],[-hw,-hd+ch]],faces=[];for(let i=0;i<8;i++){let[n0,n1]=NORMALS[i],nx=n0*cs+n1*sn,nz=-n0*sn+n1*cs;if(nz>=-1e-9)continue;let lit=Math.max(0,nx*LX+nz*LZ),tone;i%4===0?tone=56+(front-56)*Math.min(1,lit/LIT)+12*smooth(clamp2((lit-LIT)/(1-LIT))):i%4===2?tone=40+104*lit:tone=front+(48+207*lit**6-front)*live;let p=at(...loop[i]),q=at(...loop[(i+1)%8]);faces.push([Math.min(p,q),Math.max(p,q),tone*fade])}let lo=1/0,hi=-1/0;for(let f of faces)lo=Math.min(lo,f[0]),hi=Math.max(hi,f[1]);let first=-1,last=-1;for(let x=Math.max(0,Math.floor(lo));x<Math.min(width,Math.ceil(hi));x++){let cover=0,ink=0;for(let[l,h,tone2]of faces){let k=Math.max(0,Math.min(x+1,h)-Math.max(x,l));cover+=k,ink+=k*tone2}if(cover<.34)continue;let tone=ink/cover,cell;cover>=.72?cell=["\u2588",tone]:lo>x&&hi>=x+1?cell=["\u2590",tone]:hi<x+1&&lo<=x?cell=["\u258C",tone]:cell=["\u2588",tone*cover];let v=toneOf(cell[1]);v<=0||(row[x]=[cell[0],v],first<0&&(first=x),last=x)}first>0&&(row[first-1]=[" ",0]),last>=0&&last<width-1&&(row[last+1]=[" ",0])}grid.push(row)}let ly=7,lx=c+12;for(let x of[lx-1,lx+6,lx+7]){if(x<0||x>=width)continue;let tone=toneOf(grid[ly][x][1]*keep);grid[ly][x]=tone>=3?[grid[ly][x][0],tone]:[" ",0]}for(let i=0;i<6;i++){let m=mix[i];if(m<=0)continue;let tone=toneOf(grid[ly][lx+i][1]*(1-m)+176*m);grid[ly][lx+i]=tone>0?["Vercel"[i],tone]:[" ",0]}return grid}function waitingFrame2(time,width=60,alignment="left"){checkTime(time),checkLayout(width,alignment);let rows=[];for(let r=0;r<8;r++)rows.push(rowAt(time,r));let{mix,keep}=labelAt(time);return render(rows,mix,keep,width,alignment)}function settledFrame2(width=60,alignment="left"){return checkLayout(width,alignment),render(Array.from({length:8},restRow),[1,1,1,1,1,1],0,width,alignment)}let finishDuration2=3,STEP=1/30,COMMIT=.25,DRIVE=.4,DRIVE_PER=.6,CATCH=2.1,SEAT=.4,LET_GO=.35,RISE=.5,SPEC=1,WARM=.5,WAKE=.9,INK_AT=.3,INK_LEN=.4,PEAK_N=60*.4**2*.6**3,A=s=>1-6*s*s+8*s**3-3*s**4,B=s=>4*s**3-3*s**4,N=s=>60*s*s*(1-s)**3,IA=s=>s-2*s**3+2*s**4-.6*s**5,IB=s=>s**4-.6*s**5,IN=s=>20*s**3-45*s**4+36*s**5-10*s**6,checkProgress=progress=>{if(typeof progress!="number"||!Number.isFinite(progress)||progress<0||progress>1)throw new RangeError("progress must be a number from 0 to 1")};function plan(time){let rows=[],sx=0,sy=0;for(let r=0;r<8;r++){let a=rowAt(time,r),lead=(8-1-r)*STEP,th=a.th+a.v*lead;rows.push({a,lead,th}),sx+=Math.cos(2*th),sy+=Math.sin(2*th)}let mean=Math.atan2(sy,sx)/2,travel=mean-Math.PI*Math.floor(mean/Math.PI);for(travel<COMMIT*Math.PI&&(travel+=Math.PI);;){let drive=DRIVE+DRIVE_PER*travel/Math.PI,forward=!0;for(let row of rows){row.target=Math.PI*Math.round((row.th-travel)/Math.PI),row.from=row.th-row.target,row.k=-row.from/drive-.4*(row.a.v-CATCH);for(let i=0;i<=64&&forward;i++){let s=i/64;row.a.v*A(s)-CATCH*B(s)+row.k*N(s)>0&&(forward=!1)}}if(forward)return{rows,travel,drive,rest:7*STEP+drive+SEAT};travel+=Math.PI}}function poseAt(p,t){let handover=smooth(clamp2(t/LET_GO)),rise=smooth(clamp2(t/RISE)),drive=p.drive;return p.rows.map(({a,lead,target,from,k})=>{let tau=t-lead;if(tau>=drive+SEAT)return{...restRow(),angle:target};let u,v,env=0,wake=0;if(tau<0)u=a.th+a.v*t-target,v=a.v;else if(tau<drive){let s=tau/drive;u=from+drive*(a.v*IA(s)-CATCH*IB(s)+k*IN(s)),v=a.v*A(s)-CATCH*B(s)+k*N(s),env=N(s)/PEAK_N,wake=16*s*s*(1-s)**2}else{let x=(tau-drive)/SEAT;u=-CATCH*SEAT*x*(1-x)**3,v=-CATCH*(1-x)**2*(1-4*x)}return{th:u,v,angle:target+u,g:lerp(a.g,1,rise),e:lerp(a.e,WARM*env,handover),live:lerp(a.live,SPEC*env,handover),drag:a.drag*(1-handover)-WAKE*p.travel/Math.PI*wake,reach:lerp(Math.min(a.reach,9),9,rise)}})}function finishFrame2(time,progress,width=60,alignment="left"){if(checkTime(time),checkLayout(width,alignment),checkProgress(progress),progress===0)return waitingFrame2(time,width,alignment);let p=plan(time),t=progress*finishDuration2;if(progress===1||t>=p.rest)return settledFrame2(width,alignment);let label=labelAt(time),mix=label.mix.map((m0,i)=>lerp(m0,1,smooth(clamp2((t-INK_AT-i*TYPE)/INK_LEN))));return render(poseAt(p,t),mix,lerp(label.keep,0,smooth(clamp2(t/(INK_AT+INK_LEN)))),width,alignment)}return{waitingFrame:waitingFrame2,settledFrame:settledFrame2,entrance:entrance2,period:period2,finishFrame:finishFrame2,finishDuration:finishDuration2}})(),BREATH=.3,VISIT=.5,LEAD=.2,STATUS=.6,SPIN=BREATH+LEAD+STATUS/2,revealDuration=BREATH+LEAD+STATUS,clamp=n=>Math.min(1,Math.max(0,n)),ramp=(time,start,length)=>{let s=clamp((time-start)/length);return s*s*(3-2*s)};function revealFrame(time,reduced=!1){if(typeof time!="number"||!Number.isFinite(time))throw new TypeError("time must be a finite number of seconds");if(typeof reduced!="boolean")throw new TypeError("reduced must be a boolean");return reduced?{visit:1,status:1,spinner:!1,ready:!0}:time>=revealDuration?{visit:1,status:1,spinner:!0,ready:!0}:{visit:ramp(time,BREATH,VISIT),status:ramp(time,BREATH+LEAD,STATUS),spinner:time>=SPIN,ready:!1}}var import_chalk=__toESM(require_source(),1);function encodeGrid(grid,width,colors){return grid.map((row,y)=>{let result="",previous="";for(let x=0;x<width;x++){let[ch,n]=row[x];if(ch===" "||n===0){result+=" ";continue}if(!colors&&(ch==="0"||ch==="1")){let h=Math.imul(x+1,73244475)^Math.imul(y+1,668265261);if(h=Math.imul(h^h>>>16,73244475),((h^h>>>16)>>>0)/4294967296>=n/96){result+=" ";continue}}let style=colors?`\x1B[22;38;2;${colors.background.map((bg,i)=>Math.round(bg+(colors.foreground[i]-bg)*n/255)).join(";")}m`:n<96?"\x1B[2;39m":"\x1B[22;39m";style!==previous&&(result+=style,previous=style),result+=ch}return"\r\x1B[2K"+result.trimEnd()+`\x1B[0m
7
+ import{markOnboardingSeen}from"./chunk-S4AANAHX.js";import{isInteractiveHumanRun}from"./chunk-TSNRTRIM.js";import{isGuidanceEnabled}from"./chunk-TAAWMNNL.js";import{require_open}from"./chunk-PVASGBEF.js";import{getTeams}from"./chunk-DOMBKOLJ.js";import{printError}from"./chunk-33HVDSWP.js";import{TelemetryClient}from"./chunk-KDCODXVL.js";import{createDpopKey,deleteDpopKey,deviceAccessTokenRequest,deviceAuthorizationRequest,getCachedUsername,getUser,humanizePath,isDpopLoginEnabled,isOAuthError,processDeviceAuthorizationResponse,processTokenResponse}from"./chunk-Z2KANBOU.js";import{parseArguments}from"./chunk-CINNNQDJ.js";import{getTeamByIdOrSlug}from"./chunk-4SS6W6JK.js";import{getCommandName}from"./chunk-B4KA3ZH2.js";import{SPINNER,countRows,output_manager_default}from"./chunk-AP6DZGTK.js";import{require_dist}from"./chunk-MCYG7CCE.js";import{require_ansi_escapes}from"./chunk-YHPPP3SF.js";import{require_source}from"./chunk-NB2WLB3J.js";import{require_strip_ansi}from"./chunk-BULSRTQE.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_chalk3=__toESM(require_source(),1),import_error_utils=__toESM(require_dist(),1),open=__toESM(require_open(),1),import_ansi_escapes=__toESM(require_ansi_escapes(),1);import readline from"node:readline";import{KNOWN_AGENTS}from"@vercel/detect-agent";async function updateCurrentTeamAfterLogin(client,ssoTeamId){if(ssoTeamId)client.updateConfig({currentTeam:ssoTeamId});else{let user=null;try{user=await getUser(client)}catch{return output_manager_default.error("Failed to fetch the logged in user. Please try again."),1}client.updateConfig({currentTeam:user.version==="northstar"&&user.defaultTeamId?user.defaultTeamId:void 0})}}var LoginTelemetryClient=class extends TelemetryClient{trackState(...args){this.trackLoginState(...args)}trackDpopKey(storage){this.trackDpopKeyStorage(storage)}};import{performance}from"node:perf_hooks";var{waitingFrame,settledFrame,entrance,period,finishFrame,finishDuration}=(()=>{let TURN=Math.PI*2.5,SPIN2=2,BIRTH=.02,LAG=.045,GROW=.34,PEAK=TURN*2.4/SPIN2,SETTLE=.5,DRAG=3,REACH=24,LABEL_AT=1.95,TYPE=.045,FADE=.1,T0=1.56,DWELL=.8,CLIMB=.12,PUSH=.7,LATE=.5,GLOW=.3,SHEEN=.85,LEN=Math.hypot(.507,.862),LX=-.507/LEN,LZ=-.862/LEN,LIT=-LZ,S=Math.SQRT1_2,NORMALS=[[0,-1],[S,-S],[1,0],[S,S],[0,1],[-S,S],[-1,0],[-S,-S]],entrance2=2.4,period2=7,clamp2=(n,lo=0,hi=1)=>Math.min(hi,Math.max(lo,n)),smooth=n=>n*n*(3-2*n),easeOut=n=>1-(1-n)**3,lerp=(a,b,s)=>a*(1-s)+b*s,toneOf=n=>Math.max(0,Math.min(255,Math.round(n))),bit=(u,r)=>{let h=Math.imul(u,374761393)^Math.imul(r+11,668265263);return h=Math.imul(h^h>>>13,1274126177),h>>>15&1?"1":"0"},checkTime=time=>{if(typeof time!="number"||!Number.isFinite(time)||time<0)throw new RangeError("time must be a finite number of seconds >= 0")},checkLayout=(width,alignment)=>{if(width!==30&&width!==60)throw new RangeError("width must be 30 or 60");if(alignment!=="left"&&alignment!=="center")throw new RangeError("alignment must be left or center")};function rowAt(t,r){let tau=t-BIRTH-(7-r)*LAG,q=1-clamp2(tau/SPIN2),E=TURN*(8*q**3-3*q**4)/5,vE=tau>0&&tau<SPIN2?-TURN*(24*q*q-12*q**3)/(5*SPIN2):0,phi=(t-T0-(8-1-r)*CLIMB)/period2,f=phi-Math.floor(phi),w=2*Math.PI*f,turn=(1-Math.cos(w))/2,g=easeOut(clamp2(tau/GROW)),settle=1-smooth(clamp2((tau-SPIN2+SETTLE)/SETTLE));return{th:E-Math.PI*f+DWELL/2*Math.sin(w),v:vE-Math.PI/period2*(1-DWELL*Math.cos(w)),g,e:g*Math.min(1,Math.abs(vE)/PEAK+GLOW*turn),live:settle+(1-settle)*SHEEN*turn,drag:E-PUSH*(1-Math.cos(w-LATE))/2,reach:tau/.45}}let restRow=()=>({th:0,v:0,g:1,e:0,live:0,drag:0,reach:9});function labelAt(t){let mix=[];for(let i=0;i<6;i++){let start=LABEL_AT+i*TYPE;mix.push(t<start?0:smooth(clamp2((t-start)/FADE)))}return{mix,keep:t<LABEL_AT?1:1-smooth(clamp2((t-LABEL_AT)/FADE))}}function render(rows,mix,keep,width,alignment){let c=alignment==="left"?12:width/2-4,span=Math.max(c,width-c),grid=[];for(let r=0;r<8;r++){let{th,g,e,live,drag,reach}=rows[r],row=[];for(let x=0;x<width;x++){let dx=x+.5-c,nx=dx/span,k=.35+.65/(1+(dx/REACH)**2),vis=smooth(clamp2((reach-Math.abs(nx))/.3)),tone=toneOf((20+30*e*k)*(1-.72*nx*nx)*vis);row.push(tone>=3?[bit(x-Math.round(drag*DRAG*k),r),tone]:[" ",0])}if(g>0){let hw=10.5*(r+.5)/8*g,hd=8/2*g,ch=Math.min(.5*g,hw/2,hd/2),cs=Math.cos(th),sn=Math.sin(th),at=(px,pz)=>c+px*cs+pz*sn,front=244-2.6*r,fade=.5+.5*g,loop=[[-hw+ch,-hd],[hw-ch,-hd],[hw,-hd+ch],[hw,hd-ch],[hw-ch,hd],[-hw+ch,hd],[-hw,hd-ch],[-hw,-hd+ch]],faces=[];for(let i=0;i<8;i++){let[n0,n1]=NORMALS[i],nx=n0*cs+n1*sn,nz=-n0*sn+n1*cs;if(nz>=-1e-9)continue;let lit=Math.max(0,nx*LX+nz*LZ),tone;i%4===0?tone=56+(front-56)*Math.min(1,lit/LIT)+12*smooth(clamp2((lit-LIT)/(1-LIT))):i%4===2?tone=40+104*lit:tone=front+(48+207*lit**6-front)*live;let p=at(...loop[i]),q=at(...loop[(i+1)%8]);faces.push([Math.min(p,q),Math.max(p,q),tone*fade])}let lo=1/0,hi=-1/0;for(let f of faces)lo=Math.min(lo,f[0]),hi=Math.max(hi,f[1]);let first=-1,last=-1;for(let x=Math.max(0,Math.floor(lo));x<Math.min(width,Math.ceil(hi));x++){let cover=0,ink=0;for(let[l,h,tone2]of faces){let k=Math.max(0,Math.min(x+1,h)-Math.max(x,l));cover+=k,ink+=k*tone2}if(cover<.34)continue;let tone=ink/cover,cell;cover>=.72?cell=["\u2588",tone]:lo>x&&hi>=x+1?cell=["\u2590",tone]:hi<x+1&&lo<=x?cell=["\u258C",tone]:cell=["\u2588",tone*cover];let v=toneOf(cell[1]);v<=0||(row[x]=[cell[0],v],first<0&&(first=x),last=x)}first>0&&(row[first-1]=[" ",0]),last>=0&&last<width-1&&(row[last+1]=[" ",0])}grid.push(row)}let ly=7,lx=c+12;for(let x of[lx-1,lx+6,lx+7]){if(x<0||x>=width)continue;let tone=toneOf(grid[ly][x][1]*keep);grid[ly][x]=tone>=3?[grid[ly][x][0],tone]:[" ",0]}for(let i=0;i<6;i++){let m=mix[i];if(m<=0)continue;let tone=toneOf(grid[ly][lx+i][1]*(1-m)+176*m);grid[ly][lx+i]=tone>0?["Vercel"[i],tone]:[" ",0]}return grid}function waitingFrame2(time,width=60,alignment="left"){checkTime(time),checkLayout(width,alignment);let rows=[];for(let r=0;r<8;r++)rows.push(rowAt(time,r));let{mix,keep}=labelAt(time);return render(rows,mix,keep,width,alignment)}function settledFrame2(width=60,alignment="left"){return checkLayout(width,alignment),render(Array.from({length:8},restRow),[1,1,1,1,1,1],0,width,alignment)}let finishDuration2=3,STEP=1/30,COMMIT=.25,DRIVE=.4,DRIVE_PER=.6,CATCH=2.1,SEAT=.4,LET_GO=.35,RISE=.5,SPEC=1,WARM=.5,WAKE=.9,INK_AT=.3,INK_LEN=.4,PEAK_N=60*.4**2*.6**3,A=s=>1-6*s*s+8*s**3-3*s**4,B=s=>4*s**3-3*s**4,N=s=>60*s*s*(1-s)**3,IA=s=>s-2*s**3+2*s**4-.6*s**5,IB=s=>s**4-.6*s**5,IN=s=>20*s**3-45*s**4+36*s**5-10*s**6,checkProgress=progress=>{if(typeof progress!="number"||!Number.isFinite(progress)||progress<0||progress>1)throw new RangeError("progress must be a number from 0 to 1")};function plan(time){let rows=[],sx=0,sy=0;for(let r=0;r<8;r++){let a=rowAt(time,r),lead=(8-1-r)*STEP,th=a.th+a.v*lead;rows.push({a,lead,th}),sx+=Math.cos(2*th),sy+=Math.sin(2*th)}let mean=Math.atan2(sy,sx)/2,travel=mean-Math.PI*Math.floor(mean/Math.PI);for(travel<COMMIT*Math.PI&&(travel+=Math.PI);;){let drive=DRIVE+DRIVE_PER*travel/Math.PI,forward=!0;for(let row of rows){row.target=Math.PI*Math.round((row.th-travel)/Math.PI),row.from=row.th-row.target,row.k=-row.from/drive-.4*(row.a.v-CATCH);for(let i=0;i<=64&&forward;i++){let s=i/64;row.a.v*A(s)-CATCH*B(s)+row.k*N(s)>0&&(forward=!1)}}if(forward)return{rows,travel,drive,rest:7*STEP+drive+SEAT};travel+=Math.PI}}function poseAt(p,t){let handover=smooth(clamp2(t/LET_GO)),rise=smooth(clamp2(t/RISE)),drive=p.drive;return p.rows.map(({a,lead,target,from,k})=>{let tau=t-lead;if(tau>=drive+SEAT)return{...restRow(),angle:target};let u,v,env=0,wake=0;if(tau<0)u=a.th+a.v*t-target,v=a.v;else if(tau<drive){let s=tau/drive;u=from+drive*(a.v*IA(s)-CATCH*IB(s)+k*IN(s)),v=a.v*A(s)-CATCH*B(s)+k*N(s),env=N(s)/PEAK_N,wake=16*s*s*(1-s)**2}else{let x=(tau-drive)/SEAT;u=-CATCH*SEAT*x*(1-x)**3,v=-CATCH*(1-x)**2*(1-4*x)}return{th:u,v,angle:target+u,g:lerp(a.g,1,rise),e:lerp(a.e,WARM*env,handover),live:lerp(a.live,SPEC*env,handover),drag:a.drag*(1-handover)-WAKE*p.travel/Math.PI*wake,reach:lerp(Math.min(a.reach,9),9,rise)}})}function finishFrame2(time,progress,width=60,alignment="left"){if(checkTime(time),checkLayout(width,alignment),checkProgress(progress),progress===0)return waitingFrame2(time,width,alignment);let p=plan(time),t=progress*finishDuration2;if(progress===1||t>=p.rest)return settledFrame2(width,alignment);let label=labelAt(time),mix=label.mix.map((m0,i)=>lerp(m0,1,smooth(clamp2((t-INK_AT-i*TYPE)/INK_LEN))));return render(poseAt(p,t),mix,lerp(label.keep,0,smooth(clamp2(t/(INK_AT+INK_LEN)))),width,alignment)}return{waitingFrame:waitingFrame2,settledFrame:settledFrame2,entrance:entrance2,period:period2,finishFrame:finishFrame2,finishDuration:finishDuration2}})(),BREATH=.3,VISIT=.5,LEAD=.2,STATUS=.6,SPIN=BREATH+LEAD+STATUS/2,revealDuration=BREATH+LEAD+STATUS,clamp=n=>Math.min(1,Math.max(0,n)),ramp=(time,start,length)=>{let s=clamp((time-start)/length);return s*s*(3-2*s)};function revealFrame(time,reduced=!1){if(typeof time!="number"||!Number.isFinite(time))throw new TypeError("time must be a finite number of seconds");if(typeof reduced!="boolean")throw new TypeError("reduced must be a boolean");return reduced?{visit:1,status:1,spinner:!1,ready:!0}:time>=revealDuration?{visit:1,status:1,spinner:!0,ready:!0}:{visit:ramp(time,BREATH,VISIT),status:ramp(time,BREATH+LEAD,STATUS),spinner:time>=SPIN,ready:!1}}var import_chalk=__toESM(require_source(),1);function encodeGrid(grid,width,colors){return grid.map((row,y)=>{let result="",previous="";for(let x=0;x<width;x++){let[ch,n]=row[x];if(ch===" "||n===0){result+=" ";continue}if(!colors&&(ch==="0"||ch==="1")){let h=Math.imul(x+1,73244475)^Math.imul(y+1,668265261);if(h=Math.imul(h^h>>>16,73244475),((h^h>>>16)>>>0)/4294967296>=n/96){result+=" ";continue}}let style=colors?`\x1B[22;38;2;${colors.background.map((bg,i)=>Math.round(bg+(colors.foreground[i]-bg)*n/255)).join(";")}m`:n<96?"\x1B[2;39m":"\x1B[22;39m";style!==previous&&(result+=style,previous=style),result+=ch}return"\r\x1B[2K"+result.trimEnd()+`\x1B[0m
8
8
  `}).join("")}function createSignInWelcome(stream,closeInputOnSignal,colors=()=>{},onShown,layout){let columns=stream.columns,rows=stream.rows,width=columns>=61?60:30,footerRows=layout?.footerRows??0,ownedRows=9+footerRows,skipFooter=footerRows?`\x1B[${footerRows}B\r`:"",spinnerIndex=0,formatSpinnerFrame=()=>`${import_chalk.default.gray(SPINNER.frames[spinnerIndex])} ${import_chalk.default.gray("Waiting for authentication...")}`,spinnerFrame=formatSpinnerFrame(),spinnerUpdated=0,shown=!1,stopped=!1,failed=!1,timer,start=0,finishStart,finishFrom=0,keepFinal=!1,finishPromise,resolveFinish,receipt,receiptRows=0,receiptPrinted=!1,receiptQueued=!1,onReceiptShown,authComplete=!1,instructionsReady=!1,instructionsVisible=!1,skipCompletion=!1,finishDeadline,pendingWrites=0,release;function releaseErrorsWhenIdle(){!stopped||pendingWrites||release||(release=setImmediate(()=>{release=void 0,stopped&&!pendingWrites&&stream.removeListener("error",errored)}))}function writePacket(packet,next){pendingWrites++;try{stream.write(packet,error=>{pendingWrites--,error?errored():next?.(),releaseErrorsWhenIdle()})}catch{pendingWrites--,errored(),releaseErrorsWhenIdle()}}let stop=()=>{if(stopped)return;stopped=!0,clearTimeout(timer),clearTimeout(finishDeadline),stream.removeListener("resize",resized),process.removeListener("exit",exiting),process.removeListener("SIGINT",finishInterrupted);for(let[signal,handler]of signals)process.removeListener(signal,handler);let showInstructions=!authComplete&&layout?.instructions&&!instructionsVisible;shown&&!keepFinal&&!receiptQueued&&!failed&&stream.columns===columns&&stream.rows===rows&&writePacket(layout?`\x1B[${ownedRows}A`+`\r\x1B[2K
9
9
  `.repeat(8)+(showInstructions?layout.instructions:authComplete?`\r\x1B[2K
10
10
  `.repeat(footerRows):skipFooter)+"\r\x1B[2K\x1B[0m":"\x1B[9A"+`\r\x1B[2K