vercel 62.2.0 → 62.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/dist/chunks/{add-7HJR3HK7.js → add-E6SM6YUU.js} +1 -1
  2. package/dist/chunks/add-K6P7R3M4.js +8 -0
  3. package/dist/chunks/add-XZMJUVCZ.js +8 -0
  4. package/dist/chunks/build-ORM2P3M7.js +7 -0
  5. package/dist/chunks/{chunk-WW3VUXRV.js → chunk-2KCAQTPM.js} +1 -1
  6. package/dist/chunks/{chunk-NT67T6DL.js → chunk-3HO365U7.js} +1 -1
  7. package/dist/chunks/{chunk-743NGLUN.js → chunk-3P7HVGKM.js} +1 -1
  8. package/dist/chunks/{chunk-N7XPPYQQ.js → chunk-3YAQUAOG.js} +1 -1
  9. package/dist/chunks/{chunk-2RQFMCPJ.js → chunk-54SEEVOA.js} +1 -1
  10. package/dist/chunks/{chunk-UWO3M2L2.js → chunk-57NFMJ6O.js} +1 -1
  11. package/dist/chunks/chunk-5G3VXZB4.js +10 -0
  12. package/dist/chunks/{chunk-JSKSNCK2.js → chunk-6RNZA3VS.js} +1 -1
  13. package/dist/chunks/chunk-72DVIZTW.js +8 -0
  14. package/dist/chunks/{chunk-C3XFIO5L.js → chunk-7NEJJJH6.js} +1 -1
  15. package/dist/chunks/{chunk-WN6OXK2F.js → chunk-7OBZ2AM6.js} +1 -1
  16. package/dist/chunks/{chunk-UOHVKN6N.js → chunk-7W3B5AJR.js} +2 -2
  17. package/dist/chunks/{chunk-GASSNHZG.js → chunk-7X34JCBW.js} +1 -1
  18. package/dist/chunks/{chunk-3R66O72V.js → chunk-AUIBCIET.js} +1 -1
  19. package/dist/chunks/{chunk-X47XV2WG.js → chunk-B4VX6C2E.js} +1 -1
  20. package/dist/chunks/{chunk-ACCZWEKL.js → chunk-BIFJ5QEB.js} +1 -1
  21. package/dist/chunks/{chunk-ALXWJ7XN.js → chunk-DBDWXNAR.js} +1 -1
  22. package/dist/chunks/{chunk-A752WDCH.js → chunk-DJC2LX46.js} +1 -1
  23. package/dist/chunks/{chunk-M7ZGWERO.js → chunk-E4M34FSN.js} +1 -1
  24. package/dist/chunks/chunk-ETYHCI6U.js +7 -0
  25. package/dist/chunks/{chunk-WOKSTB3F.js → chunk-EWW4GCZY.js} +1 -1
  26. package/dist/chunks/chunk-EZU5U2PZ.js +7 -0
  27. package/dist/chunks/{chunk-K5WTLFS6.js → chunk-FSHYI4ZE.js} +1 -1
  28. package/dist/chunks/{chunk-N4PVXHAJ.js → chunk-G3NHWIPJ.js} +1 -1
  29. package/dist/chunks/{chunk-7JFK53D4.js → chunk-G7AD7DRG.js} +1 -1
  30. package/dist/chunks/{chunk-U6N2RNDI.js → chunk-GNJPIPBF.js} +1 -1
  31. package/dist/chunks/{chunk-CQ3RAERR.js → chunk-GTZDB7IL.js} +1 -1
  32. package/dist/chunks/{chunk-ZUYWATU5.js → chunk-GV6XYKYC.js} +1 -1
  33. package/dist/chunks/{chunk-4HXRTNAK.js → chunk-HNF6WZ5S.js} +2 -2
  34. package/dist/chunks/{chunk-JO3XBFR3.js → chunk-HTZPGIVL.js} +1 -1
  35. package/dist/chunks/{chunk-E4RLHRDF.js → chunk-IHXHZBHR.js} +1 -1
  36. package/dist/chunks/chunk-IIKYA7SM.js +9 -0
  37. package/dist/chunks/{chunk-FA6O7FPC.js → chunk-J4YZKLVO.js} +1 -1
  38. package/dist/chunks/{chunk-7T4CJ6MJ.js → chunk-J7JW6BBJ.js} +1 -1
  39. package/dist/chunks/{chunk-D5VTBRWF.js → chunk-JEYKXG6O.js} +1 -1
  40. package/dist/chunks/{chunk-C6ITILVT.js → chunk-JI2BTGLU.js} +1 -1
  41. package/dist/chunks/{chunk-VDOJERIW.js → chunk-KQM2AGUS.js} +1 -1
  42. package/dist/chunks/{chunk-LHQUNL52.js → chunk-L37LRUIN.js} +1 -1
  43. package/dist/chunks/{chunk-S5CEIACD.js → chunk-LG4JQAY7.js} +1 -1
  44. package/dist/chunks/{chunk-RFWCEREA.js → chunk-LKYVY3SY.js} +1 -1
  45. package/dist/chunks/{chunk-7IRKF3ZG.js → chunk-LOD56FYJ.js} +4 -4
  46. package/dist/chunks/chunk-LSF7FY6X.js +7 -0
  47. package/dist/chunks/{chunk-KOSM3DYE.js → chunk-LW3HJWXW.js} +1 -1
  48. package/dist/chunks/chunk-MB4RN7BI.js +9 -0
  49. package/dist/chunks/{chunk-DECIQZZQ.js → chunk-MJRZSYU2.js} +3 -3
  50. package/dist/chunks/chunk-OL3BQESW.js +21 -0
  51. package/dist/chunks/{chunk-NRN65VUM.js → chunk-OY2H4NBN.js} +1 -1
  52. package/dist/chunks/{chunk-6JU3QZ3O.js → chunk-PP36OP55.js} +1 -1
  53. package/dist/chunks/{chunk-LCWCTL6L.js → chunk-PTUZ7ATN.js} +1 -1
  54. package/dist/chunks/{chunk-LCY4SULE.js → chunk-QFVAARN7.js} +1 -1
  55. package/dist/chunks/{chunk-KG5BMLOI.js → chunk-QLJ72TJJ.js} +1 -1
  56. package/dist/chunks/{chunk-RVKOPGOI.js → chunk-QYGA4IKR.js} +1 -1
  57. package/dist/chunks/{chunk-HYW4A5B3.js → chunk-RDC4BJSR.js} +5 -5
  58. package/dist/chunks/{chunk-PV5YI2ZZ.js → chunk-ROOWZCAB.js} +1 -1
  59. package/dist/chunks/{chunk-KREBNPHL.js → chunk-SANUW37I.js} +8 -4
  60. package/dist/chunks/{chunk-VTMLKJVQ.js → chunk-SL5SJUAH.js} +1 -1
  61. package/dist/chunks/{chunk-JRU6AGXG.js → chunk-TATIUO4V.js} +1 -1
  62. package/dist/chunks/{chunk-HLVUEYOZ.js → chunk-TNERVI3E.js} +1 -1
  63. package/dist/chunks/{chunk-L46BHPRD.js → chunk-TNJVIC27.js} +1 -1
  64. package/dist/chunks/{chunk-B5PFD6Q3.js → chunk-TQ5ETS24.js} +1 -1
  65. package/dist/chunks/{chunk-7ANQHBBE.js → chunk-U4C2LU7H.js} +1 -1
  66. package/dist/chunks/{chunk-N5MNZPPJ.js → chunk-UDVWL4I4.js} +1 -1
  67. package/dist/chunks/{chunk-MK3CTSDV.js → chunk-UV4HOEHC.js} +1 -1
  68. package/dist/chunks/chunk-UZ2DSUM6.js +7 -0
  69. package/dist/chunks/chunk-VUCFX2G4.js +7 -0
  70. package/dist/chunks/chunk-VX7JFH7Q.js +7 -0
  71. package/dist/chunks/{chunk-EQHNA4BW.js → chunk-WGPFU3NA.js} +1 -1
  72. package/dist/chunks/chunk-WQLEYC3T.js +9 -0
  73. package/dist/chunks/{chunk-NESZV33T.js → chunk-WT73KR4Y.js} +1 -1
  74. package/dist/chunks/chunk-WVUD3JPC.js +10 -0
  75. package/dist/chunks/{chunk-W7PVS44H.js → chunk-XP4C5FLG.js} +1 -1
  76. package/dist/chunks/{chunk-S2LBGLRE.js → chunk-XQVD5V3T.js} +1 -1
  77. package/dist/chunks/{chunk-7POWBJDF.js → chunk-YAJFAGUO.js} +3 -3
  78. package/dist/chunks/{chunk-7I23VXBQ.js → chunk-ZXEYTD3W.js} +1 -1
  79. package/dist/chunks/clear-IWIBH2TY.js +8 -0
  80. package/dist/chunks/{compile-vercel-config-2IC23CNT.js → compile-vercel-config-B2ZES5JB.js} +1 -1
  81. package/dist/chunks/{config-T3WHONFJ.js → config-5GNX5VM2.js} +1 -1
  82. package/dist/chunks/config-BLTCR2NA.js +8 -0
  83. package/dist/chunks/config-validator.mjs +1 -1
  84. package/dist/chunks/delete-DSDSQVG7.js +9 -0
  85. package/dist/chunks/delete-TN2UUEOF.js +10 -0
  86. package/dist/chunks/{detect-projects-GJF4VXQI.js → detect-projects-AWDCPVLE.js} +1 -1
  87. package/dist/chunks/{detect-services-K3363KB7.js → detect-services-VQWDU5RR.js} +1 -1
  88. package/dist/chunks/disable-76QRXL7J.js +7 -0
  89. package/dist/chunks/discard-CWXRCRFL.js +14 -0
  90. package/dist/chunks/edit-KC6AK6DA.js +9 -0
  91. package/dist/chunks/edit-LYZPKUZY.js +8 -0
  92. package/dist/chunks/enable-ZVEULDXQ.js +7 -0
  93. package/dist/chunks/{export-CMP3APAJ.js → export-SYT5NHSM.js} +2 -2
  94. package/dist/chunks/{future-GS7ZLJ3N.js → future-YNSZJIAG.js} +1 -1
  95. package/dist/chunks/{generate-cert-for-deploy-2HHUYGHU.js → generate-cert-for-deploy-G26VGC4I.js} +1 -1
  96. package/dist/chunks/image-XAJFJ6UD.js +7 -0
  97. package/dist/chunks/{import-builders-EUOOFPHW.js → import-builders-JXIILQOI.js} +1 -1
  98. package/dist/chunks/inspect-7CODV4HJ.js +9 -0
  99. package/dist/chunks/{inspect-DYNTJMTQ.js → inspect-A76MME2I.js} +2 -2
  100. package/dist/chunks/{inspect-V7HA2GZ5.js → inspect-DF35I6AZ.js} +2 -2
  101. package/dist/chunks/{inspect-KYFVYFWX.js → inspect-HIRGIJON.js} +2 -2
  102. package/dist/chunks/inspect-JEHOMETA.js +13 -0
  103. package/dist/chunks/{list-X4MKKDJX.js → list-3KNHQV4S.js} +2 -2
  104. package/dist/chunks/{list-TSDBEAVF.js → list-M2YCP5HV.js} +2 -2
  105. package/dist/chunks/list-XNNJCS5K.js +11 -0
  106. package/dist/chunks/{login-5FMKHZVG.js → login-2GVRFOQQ.js} +1 -1
  107. package/dist/chunks/login-UM35IU3S.js +9 -0
  108. package/dist/chunks/{logs-X2OIQXGW.js → logs-HS5YRXDR.js} +1 -1
  109. package/dist/chunks/ls-ISILCAV4.js +11 -0
  110. package/dist/chunks/{ls-6EDJUUDW.js → ls-KGYG3F3A.js} +2 -2
  111. package/dist/chunks/ls-M2SGUIZK.js +8 -0
  112. package/dist/chunks/ls-WROXB2SF.js +8 -0
  113. package/dist/chunks/{ls-4W4KTJ6T.js → ls-Y3CBOCK2.js} +2 -2
  114. package/dist/chunks/{ls-HK45UWBD.js → ls-YJEUWZFT.js} +2 -2
  115. package/dist/chunks/{ls-BMAVUMXU.js → ls-Z2JKBJKR.js} +2 -2
  116. package/dist/chunks/mutate-ZCA7FKDL.js +9 -0
  117. package/dist/chunks/notifications-7QROHXJQ.js +7 -0
  118. package/dist/chunks/open-FU7OJPAY.js +7 -0
  119. package/dist/chunks/{openapi-W365UPH2.js → openapi-KGCZ7LB4.js} +1 -1
  120. package/dist/chunks/permissions-I4ZXPUVY.js +7 -0
  121. package/dist/chunks/{prompt-missing-credentials-VDR5HVA2.js → prompt-missing-credentials-YPLDAGZA.js} +1 -1
  122. package/dist/chunks/publish-6WBGPES3.js +15 -0
  123. package/dist/chunks/pull-BJUOPX3J.js +7 -0
  124. package/dist/chunks/{purchase-domain-if-available-Q7H2TGKR.js → purchase-domain-if-available-7KTEXJFK.js} +1 -1
  125. package/dist/chunks/push-ZRDFCF3D.js +7 -0
  126. package/dist/chunks/{query-ABPO2REN.js → query-RXONIAT5.js} +2 -2
  127. package/dist/chunks/{reauthenticate-3H5Q2ZWD.js → reauthenticate-7RZ2XFR4.js} +1 -1
  128. package/dist/chunks/reorder-P5LWY3FS.js +10 -0
  129. package/dist/chunks/reply-QNIIC2TP.js +9 -0
  130. package/dist/chunks/resolve-RQBKN4WL.js +12 -0
  131. package/dist/chunks/restore-NPY7XA3A.js +16 -0
  132. package/dist/chunks/{rm-KHO6RV55.js → rm-4PBTYQBF.js} +1 -1
  133. package/dist/chunks/rm-5LVIH5IE.js +8 -0
  134. package/dist/chunks/rm-GGY4TGSX.js +8 -0
  135. package/dist/chunks/rm-K3V6KVHW.js +8 -0
  136. package/dist/chunks/rm-XOE3T2QM.js +8 -0
  137. package/dist/chunks/rule-inspect-6UI5XBGA.js +8 -0
  138. package/dist/chunks/rules-MJWNYYRT.js +7 -0
  139. package/dist/chunks/{schema-EKWTCBNR.js → schema-ABJKQ6AB.js} +1 -1
  140. package/dist/chunks/{schema-FZVKQRNB.js → schema-SOV2XP24.js} +1 -1
  141. package/dist/chunks/{select-org-37C26F7T.js → select-org-G4KFHFH3.js} +1 -1
  142. package/dist/chunks/set-DJO2C6XG.js +7 -0
  143. package/dist/chunks/setup-and-link-BZCJ74II.js +7 -0
  144. package/dist/chunks/tags-DY5IM5QF.js +7 -0
  145. package/dist/chunks/{types-UN5J66MI.js → types-RHUVE4FN.js} +2 -2
  146. package/dist/chunks/{update-QY3ZME4T.js → update-6WSCOLSB.js} +2 -2
  147. package/dist/commands/build/index.js +2 -2
  148. package/dist/commands/deploy/index.js +13 -10
  149. package/dist/commands/dev/index.js +6 -6
  150. package/dist/commands/env/index.js +12 -12
  151. package/dist/commands/link/index.js +2 -2
  152. package/dist/commands/list/index.js +1 -1
  153. package/dist/commands-bulk.js +273 -273
  154. package/dist/index.js +6 -3
  155. package/dist/vc.js +2 -1
  156. package/dist/version.mjs +1 -1
  157. package/package.json +55 -55
  158. package/dist/chunks/add-Q5OZFIRM.js +0 -8
  159. package/dist/chunks/add-VLVURKGS.js +0 -8
  160. package/dist/chunks/build-MR7MUWBQ.js +0 -7
  161. package/dist/chunks/chunk-5VWK73R6.js +0 -10
  162. package/dist/chunks/chunk-ADDXKC3J.js +0 -9
  163. package/dist/chunks/chunk-AKPQWZIP.js +0 -21
  164. package/dist/chunks/chunk-CVX5X5RI.js +0 -7
  165. package/dist/chunks/chunk-HVROAV4B.js +0 -9
  166. package/dist/chunks/chunk-ILXXXXVQ.js +0 -8
  167. package/dist/chunks/chunk-NXTK7VKL.js +0 -7
  168. package/dist/chunks/chunk-PADCVJ7G.js +0 -7
  169. package/dist/chunks/chunk-PAI3WRPA.js +0 -9
  170. package/dist/chunks/chunk-PTFKU33G.js +0 -10
  171. package/dist/chunks/chunk-VZDY57PJ.js +0 -7
  172. package/dist/chunks/chunk-ZQIUMXCI.js +0 -7
  173. package/dist/chunks/clear-PPE55RPM.js +0 -8
  174. package/dist/chunks/config-G2A6KPPM.js +0 -8
  175. package/dist/chunks/delete-75SYJKNE.js +0 -10
  176. package/dist/chunks/delete-MHXN5KTO.js +0 -9
  177. package/dist/chunks/disable-OUYOHEWN.js +0 -7
  178. package/dist/chunks/discard-RXSHOY3J.js +0 -14
  179. package/dist/chunks/edit-Y7OL72ZK.js +0 -9
  180. package/dist/chunks/edit-Z5RCWPOX.js +0 -8
  181. package/dist/chunks/enable-HI2UH2NM.js +0 -7
  182. package/dist/chunks/image-SQIUEBFK.js +0 -7
  183. package/dist/chunks/inspect-2SXPXNYH.js +0 -13
  184. package/dist/chunks/inspect-J3F3U3YF.js +0 -9
  185. package/dist/chunks/list-ZQSOWXRI.js +0 -11
  186. package/dist/chunks/login-YEDMPXUF.js +0 -9
  187. package/dist/chunks/ls-LAYBQVU2.js +0 -8
  188. package/dist/chunks/ls-SQ42O6O5.js +0 -11
  189. package/dist/chunks/ls-XIJ4CY2N.js +0 -8
  190. package/dist/chunks/mutate-6FCOCHSA.js +0 -9
  191. package/dist/chunks/notifications-JTK7ZOLC.js +0 -7
  192. package/dist/chunks/open-3G4R3VIN.js +0 -7
  193. package/dist/chunks/permissions-IWUBXZBZ.js +0 -7
  194. package/dist/chunks/publish-5QKVU6YV.js +0 -15
  195. package/dist/chunks/pull-K4JQEP7N.js +0 -7
  196. package/dist/chunks/push-COILRLCW.js +0 -7
  197. package/dist/chunks/reorder-FBUQ5ET7.js +0 -10
  198. package/dist/chunks/reply-FR5VO7DA.js +0 -9
  199. package/dist/chunks/resolve-JI2ENFS6.js +0 -12
  200. package/dist/chunks/restore-LYY4BSYJ.js +0 -16
  201. package/dist/chunks/rm-C2RWWMO3.js +0 -8
  202. package/dist/chunks/rm-CYYVIF2U.js +0 -8
  203. package/dist/chunks/rm-ETLZ75RJ.js +0 -8
  204. package/dist/chunks/rm-GHSQEFRG.js +0 -8
  205. package/dist/chunks/rule-inspect-MISYALLU.js +0 -8
  206. package/dist/chunks/rules-KAGL6MH3.js +0 -7
  207. package/dist/chunks/set-5D7C6HMZ.js +0 -7
  208. package/dist/chunks/setup-and-link-H4P3FZB3.js +0 -7
  209. package/dist/chunks/tags-DVGQQZNC.js +0 -7
@@ -4,7 +4,7 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{buildCommandWithGlobalFlags}from"./chunk-5VWK73R6.js";import{quoteArg}from"./chunk-BKV35LVB.js";import{printAlignedLabel}from"./chunk-YMM3VY3J.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";var import_chalk=__toESM(require_source(),1);var CRITICAL_DELIVERY_DESCRIPTION="Critical only (escalated by Vercel Agent)";function formatMinimumSeverity(notification){let level=notification.minimumSeverityLevel;return level==="critical"?CRITICAL_DELIVERY_DESCRIPTION:level?`${level[0].toUpperCase()}${level.slice(1)} and above`:notification.type==="webhook"&&!("url"in notification.webhook)?"Details unavailable":"Rule setting"}function formatProjectScope(scope){return scope.type==="all"?"all projects":`${scope.projectName} (${scope.projectId})`}function formatNotificationExpanded(notification,index){if(notification.type==="slack")return[` ${index+1}. ${import_chalk.default.bold("Slack")} ${import_chalk.default.cyan(`#${notification.channelName}`)}`,` ${import_chalk.default.dim("Project scope:")} ${formatProjectScope(notification.projectScope)}`,` ${import_chalk.default.dim("Channel ID:")} ${notification.channelId}`,` ${import_chalk.default.dim("Slack installation ID:")} ${notification.configId}`,` ${import_chalk.default.dim("Minimum severity:")} ${formatMinimumSeverity(notification)}`].join(`
7
+ import{buildCommandWithGlobalFlags}from"./chunk-WVUD3JPC.js";import{quoteArg}from"./chunk-BKV35LVB.js";import{printAlignedLabel}from"./chunk-YMM3VY3J.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";var import_chalk=__toESM(require_source(),1);var CRITICAL_DELIVERY_DESCRIPTION="Critical only (escalated by Vercel Agent)";function formatMinimumSeverity(notification){let level=notification.minimumSeverityLevel;return level==="critical"?CRITICAL_DELIVERY_DESCRIPTION:level?`${level[0].toUpperCase()}${level.slice(1)} and above`:notification.type==="webhook"&&!("url"in notification.webhook)?"Details unavailable":"Rule setting"}function formatProjectScope(scope){return scope.type==="all"?"all projects":`${scope.projectName} (${scope.projectId})`}function formatNotificationExpanded(notification,index){if(notification.type==="slack")return[` ${index+1}. ${import_chalk.default.bold("Slack")} ${import_chalk.default.cyan(`#${notification.channelName}`)}`,` ${import_chalk.default.dim("Project scope:")} ${formatProjectScope(notification.projectScope)}`,` ${import_chalk.default.dim("Channel ID:")} ${notification.channelId}`,` ${import_chalk.default.dim("Slack installation ID:")} ${notification.configId}`,` ${import_chalk.default.dim("Minimum severity:")} ${formatMinimumSeverity(notification)}`].join(`
8
8
  `);let{webhook}=notification;return[` ${index+1}. ${import_chalk.default.bold("Webhook")}`,` ${import_chalk.default.dim("Webhook ID:")} ${webhook.id}`,` ${import_chalk.default.dim("URL:")} ${"url"in webhook?webhook.url:"Details unavailable"}`,` ${import_chalk.default.dim("Minimum severity:")} ${formatMinimumSeverity(notification)}`].join(`
9
9
  `)}function formatRuleExpanded(ruleId,notifications){let lines=[` ${import_chalk.default.bold(ruleId)}`];return notifications.length===0?lines.push(` ${import_chalk.default.dim("No notification destinations")}`):lines.push(notifications.map((notification,index)=>formatNotificationExpanded(notification,index)).join(`
10
10
 
@@ -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{resolveProjectContext}from"./chunk-EQHNA4BW.js";import{performDeviceCodeFlow}from"./chunk-6JU3QZ3O.js";import{require_json_parse_better_errors}from"./chunk-N6CNMMSZ.js";import{ensureLink,parseEnv}from"./chunk-ZQIUMXCI.js";import{require_frameworks}from"./chunk-23NBYS6R.js";import{pullSubcommand}from"./chunk-B5PFD6Q3.js";import{param}from"./chunk-SXUEGVWB.js";import{STANDARD_ENVIRONMENTS,formatProject}from"./chunk-6BZCSVH6.js";import{parseTarget}from"./chunk-R3B67TKQ.js";import{getDeployment}from"./chunk-C5KVTG2O.js";import{TelemetryClient}from"./chunk-MCCL762Q.js";import{printError}from"./chunk-7T4CJ6MJ.js";import{parseArguments}from"./chunk-LCWCTL6L.js";import{addToGitIgnore,require_lib}from"./chunk-7IRKF3ZG.js";import{buildCommandWithYes,getPreservedArgsForEnvPull,outputActionRequired,outputAgentError}from"./chunk-5VWK73R6.js";import{getFlagsSpecification}from"./chunk-PV5YI2ZZ.js";import{printAlignedLabel}from"./chunk-YMM3VY3J.js";import{isAPIError}from"./chunk-RINZXCDJ.js";import{getCommandName,getCommandNamePlain}from"./chunk-FI772UVH.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{require_dist}from"./chunk-QGIQK47P.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";var import_chalk2=__toESM(require_source(),1),import_fs_extra2=__toESM(require_lib(),1);import{closeSync,openSync,readSync}from"fs";import{resolve}from"path";import{URLSearchParams}from"url";var RECOVERABLE_CHALLENGE_CODES=new Set(["challenge_required","challenge_required_email_otp","user_auth_required"]);async function withEnvChallengeRecovery(client,fn){let hadStoredSession=!!(client.authConfig.token||client.authConfig.refreshToken);try{return await fn()}catch(error){if(!isAPIError(error))throw error;let isRecoverableChallenge=RECOVERABLE_CHALLENGE_CODES.has(error.code),isRejectedStoredSession=hadStoredSession&&error.invalidToken===!0;if(!isRecoverableChallenge&&!isRejectedStoredSession||client.authConfig.tokenSource||!client.stdin.isTTY||client.nonInteractive)throw error;output_manager_default.stopSpinner(),output_manager_default.log("Sensitive Environment Variables require fresh authentication.");let refreshToken=client.authConfig.refreshToken,acrValues=getAcrValuesFromWWWAuthenticate(error.wwwAuthenticate),tokens=isRecoverableChallenge&&refreshToken&&acrValues?await performDeviceCodeFlow(client,{refreshToken,acrValues,fallbackToLoginOnStepUpFailure:!0}):await performDeviceCodeFlow(client);if(!tokens)throw error;return client.updateAuthConfig({token:tokens.access_token,userId:void 0,expiresAt:Math.floor(Date.now()/1e3)+tokens.expires_in,refreshToken:tokens.refresh_token}),client.persistAuthConfig(),await fn()}}function getAcrValuesFromWWWAuthenticate(header){if(!header)return;let bearerIndex=header.toLowerCase().indexOf("bearer");if(bearerIndex===-1)return;let match=header.slice(bearerIndex+6).match(/(?:^|[,\s])acr_values=(?:"((?:\\.|[^"\\])*)"|([^,\s]+))/i);return match?.[1]?.replace(/\\(.)/g,"$1")??match?.[2]}async function getEnvRecords(client,projectId,source,{target,gitBranch,decrypt}={}){output_manager_default.debug(`Fetching Environment Variables of project ${projectId} and target ${target}`);let query=new URLSearchParams;if(target){let targetParam="target";target!=="production"&&target!=="preview"&&target!=="development"&&(targetParam="customEnvironmentId"),query.set(targetParam,target)}gitBranch&&query.set("gitBranch",gitBranch),decrypt&&query.set("decrypt",decrypt.toString()),source&&query.set("source",source);let url=`/v10/projects/${projectId}/env?${query}`;return withEnvChallengeRecovery(client,()=>client.fetch(url))}async function pullEnvRecords(client,projectIdOrDeploymentId,source,{target,gitBranch}={}){output_manager_default.debug(`Fetching Environment Variables of ${projectIdOrDeploymentId} and target ${target}`);let query=new URLSearchParams,url=`/v3/env/pull/${projectIdOrDeploymentId}`;return projectIdOrDeploymentId.startsWith("dpl_")||target&&(url+=`/${encodeURIComponent(target)}`,gitBranch&&(url+=`/${encodeURIComponent(gitBranch)}`)),source&&query.set("source",source),Array.from(query).length>0&&(url+=`?${query}`),withEnvChallengeRecovery(client,()=>client.fetch(url))}var import_fs_extra=__toESM(require_lib(),1);var import_chalk=__toESM(require_source(),1);async function createEnvObject(envPath){let envArr=(await(0,import_fs_extra.readFile)(envPath,"utf-8")).replace(/"/g,"").split(/\r?\n|\r/).filter(line=>/^[^#]/.test(line)).filter(line=>/=/i.test(line)),parsedEnv=parseEnv(envArr);if(Object.keys(parsedEnv).length===0){output_manager_default.debug("Failed to parse env file.");return}return parsedEnv}function findChanges(oldEnv,newEnv){let added=[],changed=[];for(let key of Object.keys(newEnv))oldEnv[key]===void 0?added.push(key):oldEnv[key]!==newEnv[key]&&changed.push(key),delete oldEnv[key];let removed=Object.keys(oldEnv);return{added,changed,removed}}function buildDeltaString(oldEnv,newEnv){let{added,changed,removed}=findChanges(oldEnv,newEnv),deltaString="";return deltaString+=import_chalk.default.green(addDeltaSection("+",changed,!0)),deltaString+=import_chalk.default.green(addDeltaSection("+",added)),deltaString+=import_chalk.default.red(addDeltaSection("-",removed)),deltaString&&import_chalk.default.gray(` Changes:
7
+ import{resolveProjectContext}from"./chunk-WGPFU3NA.js";import{performDeviceCodeFlow}from"./chunk-PP36OP55.js";import{require_json_parse_better_errors}from"./chunk-N6CNMMSZ.js";import{ensureLink,parseEnv}from"./chunk-VX7JFH7Q.js";import{require_frameworks}from"./chunk-23NBYS6R.js";import{pullSubcommand}from"./chunk-TQ5ETS24.js";import{param}from"./chunk-SXUEGVWB.js";import{STANDARD_ENVIRONMENTS,formatProject}from"./chunk-6BZCSVH6.js";import{parseTarget}from"./chunk-R3B67TKQ.js";import{getDeployment}from"./chunk-C5KVTG2O.js";import{TelemetryClient}from"./chunk-MCCL762Q.js";import{printError}from"./chunk-J7JW6BBJ.js";import{parseArguments}from"./chunk-PTUZ7ATN.js";import{addToGitIgnore,require_lib}from"./chunk-LOD56FYJ.js";import{buildCommandWithYes,getPreservedArgsForEnvPull,outputActionRequired,outputAgentError}from"./chunk-WVUD3JPC.js";import{getFlagsSpecification}from"./chunk-ROOWZCAB.js";import{printAlignedLabel}from"./chunk-YMM3VY3J.js";import{isAPIError}from"./chunk-RINZXCDJ.js";import{getCommandName,getCommandNamePlain}from"./chunk-FI772UVH.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{require_dist}from"./chunk-QGIQK47P.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";var import_chalk2=__toESM(require_source(),1),import_fs_extra2=__toESM(require_lib(),1);import{closeSync,openSync,readSync}from"fs";import{resolve}from"path";import{URLSearchParams}from"url";var RECOVERABLE_CHALLENGE_CODES=new Set(["challenge_required","challenge_required_email_otp","user_auth_required"]);async function withEnvChallengeRecovery(client,fn){let hadStoredSession=!!(client.authConfig.token||client.authConfig.refreshToken);try{return await fn()}catch(error){if(!isAPIError(error))throw error;let isRecoverableChallenge=RECOVERABLE_CHALLENGE_CODES.has(error.code),isRejectedStoredSession=hadStoredSession&&error.invalidToken===!0;if(!isRecoverableChallenge&&!isRejectedStoredSession||client.authConfig.tokenSource||!client.stdin.isTTY||client.nonInteractive)throw error;output_manager_default.stopSpinner(),output_manager_default.log("Sensitive Environment Variables require fresh authentication.");let refreshToken=client.authConfig.refreshToken,acrValues=getAcrValuesFromWWWAuthenticate(error.wwwAuthenticate),tokens=isRecoverableChallenge&&refreshToken&&acrValues?await performDeviceCodeFlow(client,{refreshToken,acrValues,fallbackToLoginOnStepUpFailure:!0}):await performDeviceCodeFlow(client);if(!tokens)throw error;return client.updateAuthConfig({token:tokens.access_token,userId:void 0,expiresAt:Math.floor(Date.now()/1e3)+tokens.expires_in,refreshToken:tokens.refresh_token}),client.persistAuthConfig(),await fn()}}function getAcrValuesFromWWWAuthenticate(header){if(!header)return;let bearerIndex=header.toLowerCase().indexOf("bearer");if(bearerIndex===-1)return;let match=header.slice(bearerIndex+6).match(/(?:^|[,\s])acr_values=(?:"((?:\\.|[^"\\])*)"|([^,\s]+))/i);return match?.[1]?.replace(/\\(.)/g,"$1")??match?.[2]}async function getEnvRecords(client,projectId,source,{target,gitBranch,decrypt}={}){output_manager_default.debug(`Fetching Environment Variables of project ${projectId} and target ${target}`);let query=new URLSearchParams;if(target){let targetParam="target";target!=="production"&&target!=="preview"&&target!=="development"&&(targetParam="customEnvironmentId"),query.set(targetParam,target)}gitBranch&&query.set("gitBranch",gitBranch),decrypt&&query.set("decrypt",decrypt.toString()),source&&query.set("source",source);let url=`/v10/projects/${projectId}/env?${query}`;return withEnvChallengeRecovery(client,()=>client.fetch(url))}async function pullEnvRecords(client,projectIdOrDeploymentId,source,{target,gitBranch}={}){output_manager_default.debug(`Fetching Environment Variables of ${projectIdOrDeploymentId} and target ${target}`);let query=new URLSearchParams,url=`/v3/env/pull/${projectIdOrDeploymentId}`;return projectIdOrDeploymentId.startsWith("dpl_")||target&&(url+=`/${encodeURIComponent(target)}`,gitBranch&&(url+=`/${encodeURIComponent(gitBranch)}`)),source&&query.set("source",source),Array.from(query).length>0&&(url+=`?${query}`),withEnvChallengeRecovery(client,()=>client.fetch(url))}var import_fs_extra=__toESM(require_lib(),1);var import_chalk=__toESM(require_source(),1);async function createEnvObject(envPath){let envArr=(await(0,import_fs_extra.readFile)(envPath,"utf-8")).replace(/"/g,"").split(/\r?\n|\r/).filter(line=>/^[^#]/.test(line)).filter(line=>/=/i.test(line)),parsedEnv=parseEnv(envArr);if(Object.keys(parsedEnv).length===0){output_manager_default.debug("Failed to parse env file.");return}return parsedEnv}function findChanges(oldEnv,newEnv){let added=[],changed=[];for(let key of Object.keys(newEnv))oldEnv[key]===void 0?added.push(key):oldEnv[key]!==newEnv[key]&&changed.push(key),delete oldEnv[key];let removed=Object.keys(oldEnv);return{added,changed,removed}}function buildDeltaString(oldEnv,newEnv){let{added,changed,removed}=findChanges(oldEnv,newEnv),deltaString="";return deltaString+=import_chalk.default.green(addDeltaSection("+",changed,!0)),deltaString+=import_chalk.default.green(addDeltaSection("+",added)),deltaString+=import_chalk.default.red(addDeltaSection("-",removed)),deltaString&&import_chalk.default.gray(` Changes:
8
8
  `)+deltaString+`
9
9
  `}function addDeltaSection(prefix,arr,changed=!1){return arr.length===0?"":arr.sort().map(item=>` ${prefix} ${item}${changed?" (Updated)":""}`).join(`
10
10
  `)+`
@@ -15,7 +15,7 @@ import{resolveProjectContext}from"./chunk-EQHNA4BW.js";import{performDeviceCodeF
15
15
  `)||valueWithoutTrailingNewline.includes("\r")?{value,strippedTrailingNewline:!1}:{value:valueWithoutTrailingNewline,strippedTrailingNewline:!0}}function getPublicPrefix(key){let upperKey=key.toUpperCase();return PUBLIC_PREFIXES.find(p=>upperKey.startsWith(p))||null}function getFrameworkPublicPrefix(frameworkSlug,key){let prefix=import_frameworks.frameworkList.find(framework=>framework.slug===frameworkSlug)?.envPrefix;return prefix&&key.toUpperCase().startsWith(prefix.toUpperCase())?prefix:null}function getApiPublicPrefix(key){let upperKey=key.toUpperCase();return API_PUBLIC_PREFIXES.find(prefix=>upperKey.startsWith(prefix))??null}function parseSvelteKitPublicEnvVarPrefix(config){if(!config.includes("publicPrefix"))return{status:"ready",prefix:null};let match=/publicPrefix:\s*(?:'(?<single>[^']*)'|"(?<double>[^"]*)"|`(?<template>[^`$]*)`)/.exec(config),prefix=match?.groups?.single??match?.groups?.double??match?.groups?.template;return prefix===void 0?{status:"unavailable"}:{status:"ready",prefix}}async function getLocalSvelteKitPublicPrefixes(cwd,rootDirectory){let projectRoot=rootDirectory?join(cwd,rootDirectory):cwd,config;try{config=await readFile2(join(projectRoot,"svelte.config.js"),"utf8")}catch{return}let parsed=parseSvelteKitPublicEnvVarPrefix(config);if(parsed.status!=="unavailable")return[parsed.prefix??"PUBLIC_","VITE_"]}function removePublicPrefix(key){let prefix=getPublicPrefix(key);return prefix?key.slice(prefix.length):key}async function validateEnvValue(opts){let finalValue=opts.initialValue,alreadyConfirmed=!1;if(opts.skipConfirm){let valueWarnings=getEnvValueWarnings(finalValue),warningMessage=formatWarnings(valueWarnings);warningMessage&&opts.showWarning(warningMessage)}else{let valueAccepted=!1;for(;!valueAccepted;){let valueWarnings=getEnvValueWarnings(finalValue),warningMessage=formatWarnings(valueWarnings);if(!warningMessage){valueAccepted=!0;break}opts.showWarning(warningMessage);let choices=hasOnlyWhitespaceWarnings(valueWarnings)?[{name:"Leave as is",value:"c"},{name:"Re-enter",value:"r"},{name:"Trim whitespace",value:"t"}]:[{name:"Leave as is",value:"c"},{name:"Re-enter",value:"r"}],action=await opts.selectAction(choices);action==="c"?(valueAccepted=!0,valueWarnings.some(w=>w.requiresConfirmation)&&(alreadyConfirmed=!0)):action==="t"?(finalValue=trimValue(finalValue),opts.showLog("Trimmed whitespace")):finalValue=await opts.promptForValue()}}return{finalValue,alreadyConfirmed}}function getEnvKeyWarnings(key){let warnings=[],matchingPrefix=getPublicPrefix(key);if(matchingPrefix){let nameWithoutPrefix=key.slice(matchingPrefix.length);looksLikeSecret(nameWithoutPrefix)&&getMatchingServerOnlyKey(nameWithoutPrefix)?warnings.push({message:`\`${matchingPrefix}\` exposes \`${key}\` to anyone visiting your site`,requiresConfirmation:!0}):warnings.push({message:`\`${matchingPrefix}\` exposes this value to anyone visiting your site`,requiresConfirmation:!1})}return warnings}var ENV_VISIBILITY_DEPRECATION_MESSAGE="`--visibility` is deprecated. Use `--type` instead.";function invalidTypeOptionError(optionName,value){if(!(value==="config"||value==="secret"))return value==="sensitive"?`The \`${optionName}\` flag accepts \`config\` or \`secret\`. Use \`--type secret\` or the legacy \`--sensitive\` flag.`:value==="plain"||value==="encrypted"?`The \`${optionName}\` flag accepts \`config\` or \`secret\`. Use \`--type config\` for readable values.`:`The \`${optionName}\` flag must be either \`config\` or \`secret\`.`}function resolveEnvVarTypeOption(options){let usedDeprecatedVisibility=options.visibility!==void 0;if(options.type!==void 0){let error=invalidTypeOptionError("--type",options.type);if(error)return{usedDeprecatedVisibility,error,errorReason:"invalid_type"}}if(options.visibility!==void 0){let error=invalidTypeOptionError("--visibility",options.visibility);if(error)return{usedDeprecatedVisibility,error,errorReason:"invalid_visibility"}}return options.type!==void 0&&options.visibility!==void 0&&options.type!==options.visibility?{usedDeprecatedVisibility,error:`\`--type ${options.type}\` conflicts with \`--visibility ${options.visibility}\`. \`--visibility\` is a deprecated alias of \`--type\`; remove it.`,errorReason:"conflicting_type_visibility"}:options.type!==void 0?{explicitVisibility:options.type,source:"type",usedDeprecatedVisibility}:options.visibility!==void 0?{explicitVisibility:options.visibility,source:"visibility",usedDeprecatedVisibility}:{usedDeprecatedVisibility}}function isSecretEnvVar(env){return env.type==="sensitive"||env.visibility==="secret"}function formatVisibilityLabel(visibility,type){let resolved=visibility??visibilityFromEnvType(type);if(resolved==="config")return"Config";if(resolved==="secret")return"Secret"}function visibilityFromEnvType(type){if(type==="sensitive")return"secret";if(type==="plain"||type==="encrypted")return"config"}function hasNonDevelopmentTarget(envTargets){return envTargets.some(target=>target!=="development")}function getPublicPrefixSecretVisibilityError(key,options){let publicPrefix=getApiPublicPrefix(key);if(!publicPrefix||!(options.visibility==="secret"||options.type==="sensitive"))return null;let privateKey=key.slice(publicPrefix.length);return options.context==="update"?`\`${publicPrefix}\` exposes this value to anyone visiting your site, so \`${key}\` cannot be a Secret. To keep it private, add \`${privateKey}\` as a Secret, then remove \`${key}\`. If the value is safe to expose, keep it as Config.`:`\`${publicPrefix}\` exposes this value to anyone visiting your site, so \`${key}\` cannot be a Secret. To keep it private, rename the variable to \`${privateKey}\` and keep the Secret type. If the value is safe to expose, use \`--type config\`.`}function shouldOmitInferredVisibility(key,envTargets,teamSensitivePolicyOn){return!getApiPublicPrefix(key)||!hasNonDevelopmentTarget(envTargets)?!1:teamSensitivePolicyOn}function resolveEnvVarVisibility(options){if(options.explicitVisibility!==void 0){if(options.explicitVisibility!=="config"&&options.explicitVisibility!=="secret"){let optionName=options.explicitOptionSource==="visibility"?"--visibility":"--type";return{error:options.explicitVisibility==="sensitive"?`The \`${optionName}\` flag accepts \`config\` or \`secret\`. Use \`--type secret\` or the legacy \`--sensitive\` flag.`:options.explicitVisibility==="plain"||options.explicitVisibility==="encrypted"?`The \`${optionName}\` flag accepts \`config\` or \`secret\`. Use \`--type config\` for readable values.`:`The \`${optionName}\` flag must be either \`config\` or \`secret\`.`}}let publicPrefixError2=getPublicPrefixSecretVisibilityError(options.key,{visibility:options.explicitVisibility,type:options.type,context:options.context});return publicPrefixError2?{error:publicPrefixError2}:{visibility:options.explicitVisibility}}let inferred=visibilityFromEnvType(options.type);if(inferred===void 0)return{};if(shouldOmitInferredVisibility(options.key,options.envTargets,options.teamSensitivePolicyOn))return{};let publicPrefixError=getPublicPrefixSecretVisibilityError(options.key,{visibility:inferred,type:options.type,context:options.context});return publicPrefixError?{error:publicPrefixError}:{visibility:inferred}}function getUnavailableSecretValuesMessage(environment,count){let values=count===1?"value":"values";return environment==="development"?`${count} Development Secret ${values} ${count===1?"was":"were"} not returned by Vercel.`:`${count} Secret ${values} cannot be pulled from the \`${environment}\` Environment.`}function getLocalSecretFallbackMessage(count){return` Define ${count===1?"it":"them"} in a local .env file.`}var CONTENTS_HEADER="# Created by Vercel CLI";function updateOidcTokenContents(existing,token){let assignment=`${VERCEL_OIDC_TOKEN}="${escapeValue(token)}"`,oidcAssignment=new RegExp(`^(\\uFEFF?)[\\t ]*(?:export[\\t ]+)?${VERCEL_OIDC_TOKEN}[\\t ]*=[^\\r\\n]*(\\r\\n|\\n|\\r|$)`,"gm"),tokenWritten=!1,withoutDuplicates=existing.replace(oidcAssignment,(_match,byteOrderMark,lineEnding2)=>token!==void 0&&!tokenWritten?(tokenWritten=!0,`${byteOrderMark}${assignment}${lineEnding2}`):byteOrderMark);if(token===void 0||tokenWritten)return withoutDuplicates;let lineEnding=withoutDuplicates.match(/\r\n|\n|\r/)?.[0]??`
16
16
  `,hasTrailingLineEnding=/(?:\r\n|\n|\r)$/.test(withoutDuplicates),hasTrailingBlankLine=/(?:\r\n|\n|\r){2}$/.test(withoutDuplicates),separator=withoutDuplicates.length===0||hasTrailingBlankLine?"":hasTrailingLineEnding?lineEnding:`${lineEnding}${lineEnding}`;return`${withoutDuplicates}${separator}${CONTENTS_HEADER}${lineEnding}${assignment}${lineEnding}`}function escapeValue(value){return value?value.replace(/\n/g,"\\n").replace(/\r/g,"\\r"):""}var import_error_utils=__toESM(require_dist(),1);var import_json_parse_better_errors=__toESM(require_json_parse_better_errors(),1);var EnvPullTelemetryClient=class extends TelemetryClient{trackCliArgumentFilename(filename){filename&&this.trackCliArgument({arg:"filename",value:this.redactedValue})}trackCliOptionEnvironment(environment){environment&&this.trackCliOption({option:"environment",value:STANDARD_ENVIRONMENTS.includes(environment)?environment:this.redactedValue})}trackCliOptionGitBranch(gitBranch){gitBranch&&this.trackCliOption({option:"git-branch",value:this.redactedValue})}trackCliFlagYes(yes){yes&&this.trackCliFlag("yes")}trackCliOptionId(id){id&&this.trackCliOption({option:"id",value:this.redactedValue})}};var CONTENTS_PREFIX=`# Created by Vercel CLI
17
17
  `;function printEnvPullWarning(message){output_manager_default.print(`${import_chalk2.default.yellow("!")} ${message}
18
- `)}function readHeadSync(path,length){let buffer=Buffer.alloc(length),fd=openSync(path,"r");try{readSync(fd,buffer,0,buffer.length,null)}finally{closeSync(fd)}return buffer.toString()}function tryReadHeadSync(path,length){try{return readHeadSync(path,length)}catch(err){if(!(0,import_error_utils.isErrnoException)(err)||err.code!=="ENOENT")throw err}}var VARIABLES_TO_IGNORE=["VERCEL_ANALYTICS_ID","VERCEL_SPEED_INSIGHTS_ID","VERCEL_WEB_ANALYTICS_ID"],SENSITIVE_PLACEHOLDER=SENSITIVE_ENV_VALUE_PLACEHOLDER;async function getRedactedSensitiveKeys(client,projectId,source,target,gitBranch,records){let emptyKeys=Object.keys(records).filter(key=>!records[key]);if(!projectId||emptyKeys.length===0)return new Set;try{let{envs}=await getEnvRecords(client,projectId,source,{target,gitBranch}),sensitiveKeys=new Set(envs.filter(isSecretEnvVar).map(env=>env.key));return new Set(emptyKeys.filter(key=>sensitiveKeys.has(key)))}catch{return new Set}}async function pull(client,argv,source="vercel-cli:env:pull",options={}){let telemetryClient=new EnvPullTelemetryClient({opts:{store:client.telemetryEventStore}}),parsedArgs,flagsSpecification=getFlagsSpecification(pullSubcommand.options);try{parsedArgs=parseArguments(argv,flagsSpecification)}catch(err){return printError(err),1}let{args,flags:opts}=parsedArgs;if(args.length>1)return output_manager_default.error(`Invalid number of arguments. Usage: ${getCommandName("env pull <file>")}`),1;let[rawFilename]=args,filename=rawFilename||".env.local",skipConfirmation=opts["--yes"],gitBranch=opts["--git-branch"];telemetryClient.trackCliArgumentFilename(args[0]),telemetryClient.trackCliFlagYes(skipConfirmation),telemetryClient.trackCliOptionGitBranch(gitBranch),telemetryClient.trackCliOptionEnvironment(opts["--environment"]),telemetryClient.trackCliOptionId(opts["--id"]),telemetryClient.trackCliOptionProject(opts["--project"]);let link=await resolveProjectContext({client,projectNameOrId:opts["--project"],skipOwnerLookup:!0});if(link.status==="error")return link.exitCode;if(link.status==="not_linked"){if(client.nonInteractive){let preserved=getPreservedArgsForEnvPull(client.argv),linkArgv=[...client.argv.slice(0,2),"link","--scope","<scope>",...preserved];outputAgentError(client,{status:"error",reason:"not_linked",message:`Your codebase isn't linked to a project on Vercel. Run \`${getCommandNamePlain("link")}\` to begin. Use \`--yes\` for non-interactive; use \`--scope\` or \`--project\` to specify team or project.`,next:[{command:buildCommandWithYes(linkArgv)},{command:buildCommandWithYes(client.argv)}]},1)}if(!client.nonInteractive&&client.stdin.isTTY&&!skipConfirmation){let ensuredLink=await ensureLink("env pull",client,client.cwd,{link,pullEnv:!1});if(typeof ensuredLink=="number")return ensuredLink;link=ensuredLink}else return output_manager_default.error(`Your codebase isn\u2019t linked to a project on Vercel. Run ${getCommandName("link")} to begin.`),1}client.config.currentTeam=link.org.type==="team"?link.org.id:void 0;let deploymentId=opts["--id"];if(deploymentId&&opts["--project"]){let deployment=await getDeployment(client,link.org.slug||link.org.id,deploymentId);if(deployment.projectId&&deployment.projectId!==link.project.id)return output_manager_default.error(`Deployment ${import_chalk2.default.bold(deploymentId)} does not belong to project ${import_chalk2.default.bold(link.project.name)}.`),1}let environment=parseTarget({flagName:"environment",flags:opts})||"development";return await envPullCommandLogic(client,filename,!!skipConfirmation,environment,link,gitBranch,client.cwd,source,deploymentId,options),0}async function envPullCommandLogic(client,filename,skipConfirmation,environment,link,gitBranch,cwd,source,deploymentId,{oidcTokenOnly=!1}={}){let fullPath=resolve(cwd,filename),head=tryReadHeadSync(fullPath,Buffer.byteLength(CONTENTS_PREFIX)),exists=typeof head<"u";if(head===CONTENTS_PREFIX&&!oidcTokenOnly)output_manager_default.log(`Overwriting existing ${import_chalk2.default.bold(filename)} file`);else if(exists&&!skipConfirmation&&!oidcTokenOnly){if(client.nonInteractive){let preserved=getPreservedArgsForEnvPull(client.argv).filter(arg=>arg!=="--yes"&&arg!=="-y"),suffix=preserved.length>0?` ${preserved.join(" ")}`:"";outputActionRequired(client,{status:"action_required",reason:"env_file_exists",message:`File ${param(filename)} already exists and was not created by Vercel CLI. Use --yes to overwrite or specify a different filename.`,next:[{command:getCommandNamePlain(`env pull ${filename} --yes${suffix}`),when:"Overwrite this file"},{command:getCommandNamePlain(`env pull <filename>${suffix}`),when:"Use a different filename"}]})}if(!await client.input.confirm(`Found existing file ${param(filename)}. Do you want to overwrite?`,!1)){output_manager_default.log("Canceled");return}}let projectSlugLink=link.org.slug?formatProject(link.org.slug,link.project.name):import_chalk2.default.bold(link.project.name),downloadMessage=oidcTokenOnly?`Downloading a fresh \`${import_chalk2.default.cyan(VERCEL_OIDC_TOKEN)}\` for ${projectSlugLink}`:gitBranch?`Downloading \`${import_chalk2.default.cyan(environment)}\` environment variables for ${projectSlugLink} and any overrides for branch ${import_chalk2.default.cyan(gitBranch)}`:`Downloading \`${import_chalk2.default.cyan(environment)}\` environment variables for ${projectSlugLink}`;output_manager_default.log(downloadMessage),output_manager_default.spinner("Downloading");let pullId=deploymentId||link.project.id,pullResult=await pullEnvRecords(client,pullId,source,{target:environment||"development",gitBranch}),records=deploymentId?pullResult.buildEnv:pullResult.env,deltaString="",oldEnv;exists&&!oidcTokenOnly&&(oldEnv=await createEnvObject(fullPath));let contents,fileChanged=!0,keptLocalKeys=[],preservedLocalSecretKeys=[],redactedSecretCount=0,placeholderSecretCount=0;if(oidcTokenOnly){let existingContents=exists?await(0,import_fs_extra2.readFile)(fullPath,"utf8"):"";contents=updateOidcTokenContents(existingContents,records[VERCEL_OIDC_TOKEN]||void 0),fileChanged=contents!==existingContents}else{let sensitiveKeys=await getRedactedSensitiveKeys(client,deploymentId?void 0:link.project.id,source,environment,gitBranch,records);redactedSecretCount=sensitiveKeys.size;let mergedRecords={...records};for(let key of sensitiveKeys){let localValue=oldEnv?.[key];localValue&&localValue!==SENSITIVE_PLACEHOLDER?(mergedRecords[key]=localValue,preservedLocalSecretKeys.push(key)):(mergedRecords[key]=SENSITIVE_PLACEHOLDER,placeholderSecretCount++)}if(oldEnv)for(let[key,value]of Object.entries(oldEnv))!(key in mergedRecords)&&key!==VERCEL_OIDC_TOKEN&&!VARIABLES_TO_IGNORE.includes(key)&&(mergedRecords[key]=value,keptLocalKeys.push(key));if(contents=CONTENTS_PREFIX+Object.keys(mergedRecords).sort().filter(key=>!VARIABLES_TO_IGNORE.includes(key)).map(key=>`${key}="${escapeValue2(mergedRecords[key])}"`).join(`
18
+ `)}function readHeadSync(path,length){let buffer=Buffer.alloc(length),fd=openSync(path,"r");try{readSync(fd,buffer,0,buffer.length,null)}finally{closeSync(fd)}return buffer.toString()}function tryReadHeadSync(path,length){try{return readHeadSync(path,length)}catch(err){if(!(0,import_error_utils.isErrnoException)(err)||err.code!=="ENOENT")throw err}}var VARIABLES_TO_IGNORE=["VERCEL_ANALYTICS_ID","VERCEL_SPEED_INSIGHTS_ID","VERCEL_WEB_ANALYTICS_ID"],SENSITIVE_PLACEHOLDER=SENSITIVE_ENV_VALUE_PLACEHOLDER;async function getRedactedSensitiveKeys(client,projectId,source,target,gitBranch,records){let emptyKeys=Object.keys(records).filter(key=>!records[key]);if(!projectId||emptyKeys.length===0)return new Set;try{let{envs}=await getEnvRecords(client,projectId,source,{target,gitBranch}),sensitiveKeys=new Set(envs.filter(isSecretEnvVar).map(env=>env.key));return new Set(emptyKeys.filter(key=>sensitiveKeys.has(key)))}catch{return new Set}}async function pull(client,argv,source="vercel-cli:env:pull",options={}){let telemetryClient=new EnvPullTelemetryClient({opts:{store:client.telemetryEventStore}}),parsedArgs,flagsSpecification=getFlagsSpecification(pullSubcommand.options);try{parsedArgs=parseArguments(argv,flagsSpecification)}catch(err){return printError(err),2}let{args,flags:opts}=parsedArgs;if(args.length>1)return output_manager_default.error(`Invalid number of arguments. Usage: ${getCommandName("env pull <file>")}`),2;let[rawFilename]=args,filename=rawFilename||".env.local",skipConfirmation=opts["--yes"],gitBranch=opts["--git-branch"];telemetryClient.trackCliArgumentFilename(args[0]),telemetryClient.trackCliFlagYes(skipConfirmation),telemetryClient.trackCliOptionGitBranch(gitBranch),telemetryClient.trackCliOptionEnvironment(opts["--environment"]),telemetryClient.trackCliOptionId(opts["--id"]),telemetryClient.trackCliOptionProject(opts["--project"]);let link=await resolveProjectContext({client,projectNameOrId:opts["--project"],skipOwnerLookup:!0});if(link.status==="error")return link.exitCode;if(link.status==="not_linked"){if(client.nonInteractive){let preserved=getPreservedArgsForEnvPull(client.argv),linkArgv=[...client.argv.slice(0,2),"link","--scope","<scope>",...preserved];outputAgentError(client,{status:"error",reason:"not_linked",message:`Your codebase isn't linked to a project on Vercel. Run \`${getCommandNamePlain("link")}\` to begin. Use \`--yes\` for non-interactive; use \`--scope\` or \`--project\` to specify team or project.`,next:[{command:buildCommandWithYes(linkArgv)},{command:buildCommandWithYes(client.argv)}]},1)}if(!client.nonInteractive&&client.stdin.isTTY&&!skipConfirmation){let ensuredLink=await ensureLink("env pull",client,client.cwd,{link,pullEnv:!1});if(typeof ensuredLink=="number")return ensuredLink;link=ensuredLink}else return output_manager_default.error(`Your codebase isn\u2019t linked to a project on Vercel. Run ${getCommandName("link")} to begin.`),1}client.config.currentTeam=link.org.type==="team"?link.org.id:void 0;let deploymentId=opts["--id"];if(deploymentId&&opts["--project"]){let deployment=await getDeployment(client,link.org.slug||link.org.id,deploymentId);if(deployment.projectId&&deployment.projectId!==link.project.id)return output_manager_default.error(`Deployment ${import_chalk2.default.bold(deploymentId)} does not belong to project ${import_chalk2.default.bold(link.project.name)}.`),1}let environment=parseTarget({flagName:"environment",flags:opts})||"development";return await envPullCommandLogic(client,filename,!!skipConfirmation,environment,link,gitBranch,client.cwd,source,deploymentId,options),0}async function envPullCommandLogic(client,filename,skipConfirmation,environment,link,gitBranch,cwd,source,deploymentId,{oidcTokenOnly=!1}={}){let fullPath=resolve(cwd,filename),head=tryReadHeadSync(fullPath,Buffer.byteLength(CONTENTS_PREFIX)),exists=typeof head<"u";if(head===CONTENTS_PREFIX&&!oidcTokenOnly)output_manager_default.log(`Overwriting existing ${import_chalk2.default.bold(filename)} file`);else if(exists&&!skipConfirmation&&!oidcTokenOnly){if(client.nonInteractive){let preserved=getPreservedArgsForEnvPull(client.argv).filter(arg=>arg!=="--yes"&&arg!=="-y"),suffix=preserved.length>0?` ${preserved.join(" ")}`:"";outputActionRequired(client,{status:"action_required",reason:"env_file_exists",message:`File ${param(filename)} already exists and was not created by Vercel CLI. Use --yes to overwrite or specify a different filename.`,next:[{command:getCommandNamePlain(`env pull ${filename} --yes${suffix}`),when:"Overwrite this file"},{command:getCommandNamePlain(`env pull <filename>${suffix}`),when:"Use a different filename"}]})}if(!await client.input.confirm(`Found existing file ${param(filename)}. Do you want to overwrite?`,!1)){output_manager_default.log("Canceled");return}}let projectSlugLink=link.org.slug?formatProject(link.org.slug,link.project.name):import_chalk2.default.bold(link.project.name),downloadMessage=oidcTokenOnly?`Downloading a fresh \`${import_chalk2.default.cyan(VERCEL_OIDC_TOKEN)}\` for ${projectSlugLink}`:gitBranch?`Downloading \`${import_chalk2.default.cyan(environment)}\` environment variables for ${projectSlugLink} and any overrides for branch ${import_chalk2.default.cyan(gitBranch)}`:`Downloading \`${import_chalk2.default.cyan(environment)}\` environment variables for ${projectSlugLink}`;output_manager_default.log(downloadMessage),output_manager_default.spinner("Downloading");let pullId=deploymentId||link.project.id,pullResult=await pullEnvRecords(client,pullId,source,{target:environment||"development",gitBranch}),records=deploymentId?pullResult.buildEnv:pullResult.env,deltaString="",oldEnv;exists&&!oidcTokenOnly&&(oldEnv=await createEnvObject(fullPath));let contents,fileChanged=!0,keptLocalKeys=[],preservedLocalSecretKeys=[],redactedSecretCount=0,placeholderSecretCount=0;if(oidcTokenOnly){let existingContents=exists?await(0,import_fs_extra2.readFile)(fullPath,"utf8"):"";contents=updateOidcTokenContents(existingContents,records[VERCEL_OIDC_TOKEN]||void 0),fileChanged=contents!==existingContents}else{let sensitiveKeys=await getRedactedSensitiveKeys(client,deploymentId?void 0:link.project.id,source,environment,gitBranch,records);redactedSecretCount=sensitiveKeys.size;let mergedRecords={...records};for(let key of sensitiveKeys){let localValue=oldEnv?.[key];localValue&&localValue!==SENSITIVE_PLACEHOLDER?(mergedRecords[key]=localValue,preservedLocalSecretKeys.push(key)):(mergedRecords[key]=SENSITIVE_PLACEHOLDER,placeholderSecretCount++)}if(oldEnv)for(let[key,value]of Object.entries(oldEnv))!(key in mergedRecords)&&key!==VERCEL_OIDC_TOKEN&&!VARIABLES_TO_IGNORE.includes(key)&&(mergedRecords[key]=value,keptLocalKeys.push(key));if(contents=CONTENTS_PREFIX+Object.keys(mergedRecords).sort().filter(key=>!VARIABLES_TO_IGNORE.includes(key)).map(key=>`${key}="${escapeValue2(mergedRecords[key])}"`).join(`
19
19
  `)+`
20
20
  `,oldEnv){let newEnv=(0,import_json_parse_better_errors.default)(JSON.stringify(mergedRecords).replace(/\\"/g,""));deltaString=buildDeltaString(oldEnv,newEnv)}}if(fileChanged&&await(0,import_fs_extra2.outputFile)(fullPath,contents,"utf8"),deltaString?output_manager_default.print(`
21
21
  `+deltaString):oldEnv&&exists&&output_manager_default.log("No changes found."),keptLocalKeys.length>0&&output_manager_default.log(`Kept ${keptLocalKeys.sort().map(key=>import_chalk2.default.bold(key)).join(", ")} (defined locally, not found in the ${import_chalk2.default.cyan(environment)} Environment)`),redactedSecretCount>0){let preservedMessage=preservedLocalSecretKeys.length>0?` Kept ${preservedLocalSecretKeys.length} existing local ${preservedLocalSecretKeys.length===1?"value":"values"}.`:"",placeholderMessage=placeholderSecretCount>0?` Wrote "${SENSITIVE_PLACEHOLDER}" ${placeholderSecretCount===1?"as a placeholder":"as placeholders"} for the remaining ${placeholderSecretCount===1?"value":"values"}; replace ${placeholderSecretCount===1?"it":"them"} with local-only values.`:"";printEnvPullWarning(`${getUnavailableSecretValuesMessage(environment,redactedSecretCount)}${preservedMessage}${placeholderMessage}`)}let isGitIgnoreUpdated=!1,fileExistsAfterPull=exists||contents.length>0;if(filename===".env.local"&&fileExistsAfterPull){let rootPath=link.repoRoot??cwd;isGitIgnoreUpdated=await addToGitIgnore(rootPath,".env*")}if(!fileChanged&&!isGitIgnoreUpdated){output_manager_default.stopSpinner();return}if(output_manager_default.print(`
@@ -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{resolveProjectContext}from"./chunk-EQHNA4BW.js";import{AGENT_REASON,AGENT_STATUS}from"./chunk-CVX5X5RI.js";import{printError}from"./chunk-7T4CJ6MJ.js";import{parseArguments}from"./chunk-LCWCTL6L.js";import{buildCommandWithYes,outputAgentError,withGlobalFlags}from"./chunk-5VWK73R6.js";import{getFlagsSpecification,getGlobalFlagsFromArgs}from"./chunk-PV5YI2ZZ.js";import{getCommandName,getCommandNamePlain}from"./chunk-FI772UVH.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";async function requireProjectContext(client,command,projectName){let link=await resolveProjectContext({client,projectNameOrId:projectName});if(link.status==="error")return link.exitCode;if(link.status==="not_linked"){if(client.nonInteractive)if(command==="redirects"){let linkCmd=getCommandNamePlain("link");outputAgentError(client,{status:AGENT_STATUS.ERROR,reason:AGENT_REASON.NOT_LINKED,message:`Your codebase isn't linked to a project on Vercel. Run ${linkCmd} to begin.`,next:[{command:linkCmd}]},1)}else{let flags=getGlobalFlagsFromArgs(client.argv.slice(2)),cmd=getCommandNamePlain(`link ${flags.join(" ")}`.trim());return outputAgentError(client,{status:AGENT_STATUS.ERROR,reason:AGENT_REASON.NOT_LINKED,userActionRequired:!0,message:`Your codebase is not linked to a Vercel project. Run link first, then retry ${command} commands.`,next:[{command:cmd,when:"to link this directory to a project"}]},1),1}return output_manager_default.error(`Your codebase isn't linked to a project on Vercel. Run ${getCommandName("link")} to begin.`),1}return client.config.currentTeam=link.org.type==="team"?link.org.id:void 0,link}function parseSubcommandArguments(argv,command){let flagsSpecification=getFlagsSpecification(command.options);return parseArguments(argv,flagsSpecification)}function validateRequiredArguments(args,required){for(let i=0;i<required.length;i++)if(!args[i])return`Missing required argument: ${required[i]}`;return null}var ROUTE_TYPE_LABELS={rewrite:"Rewrite",redirect:"Redirect",set_status:"Set Status",transform:"Transform"};function getRouteTypeLabel(rule){return rule.routeType?ROUTE_TYPE_LABELS[rule.routeType]??"-":"-"}var SRC_SYNTAX_LABELS={equals:"Exact Match","path-to-regexp":"Pattern",regex:"Regex"};function getSrcSyntaxLabel(rule){let syntax=rule.srcSyntax??"regex";return SRC_SYNTAX_LABELS[syntax]}function isTargetTransform(transform){return"target"in transform}var import_chalk=__toESM(require_source(),1);function withGlobalFlags2(client,commandTemplate){return withGlobalFlags(client,commandTemplate,{preserveProject:!0})}function shellQuoteRouteIdentifierForSuggestion(identifier){return identifier.includes(" ")?identifier.includes("'")?identifier.includes('"')?`"${identifier.replace(/"/g,'\\"')}"`:`"${identifier}"`:`'${identifier}'`:identifier}async function parseSubcommandArgs(argv,command,client){let parsedArgs;try{parsedArgs=parseSubcommandArguments(argv,command)}catch(err){if(client?.nonInteractive){let rawMessage=err instanceof Error?err.message:String(err),flags=getGlobalFlagsFromArgs(client.argv.slice(2),{preserveProject:!0}),message=rawMessage,next=[{command:getCommandNamePlain(`routes ${command.name} ${flags.join(" ")}`.trim()),when:"fix flags and retry"}],aiIdx=argv.indexOf("--ai");return(aiIdx!==-1&&(aiIdx===argv.length-1||argv[aiIdx+1]!==void 0&&argv[aiIdx+1].startsWith("-"))||/option requires argument.*--ai|--ai.*requires argument/i.test(rawMessage))&&(command.name==="add"||command.name==="edit")&&(message=command.name==="add"?'--ai requires a description. Example: routes add --ai <description> --yes --non-interactive. Replace <description> with your text; use shell quotes if it contains spaces (e.g. --ai "Redirect /old to /new").':"--ai requires a description. Example: routes edit <name-or-id> --ai <description> --yes --non-interactive. Replace placeholders; use shell quotes for <description> if it contains spaces.",next=[{command:withGlobalFlags2(client,command.name==="add"?"routes add --ai <description> --yes":"routes edit <name-or-id> --ai <description> --yes"),when:"replace <description> with your text (quote it in the shell if it contains spaces), then run"},{command:getCommandNamePlain(`routes ${command.name} --help ${flags.join(" ")}`.trim()),when:"see all flags"}]),outputAgentError(client,{status:AGENT_STATUS.ERROR,reason:AGENT_REASON.INVALID_ARGUMENTS,message,next},1),1}return printError(err),1}return parsedArgs}async function confirmAction(client,skipConfirmation,message,details){return skipConfirmation?!0:client.nonInteractive?(outputAgentError(client,{status:AGENT_STATUS.ERROR,reason:AGENT_REASON.CONFIRMATION_REQUIRED,message:`${message} Re-run with --yes to confirm.`,next:[{command:buildCommandWithYes(client.argv),when:"re-run with --yes to confirm"}]}),process.exit(1),!1):(details&&output_manager_default.print(` ${details}
7
+ import{resolveProjectContext}from"./chunk-WGPFU3NA.js";import{printError}from"./chunk-J7JW6BBJ.js";import{parseArguments}from"./chunk-PTUZ7ATN.js";import{AGENT_REASON,AGENT_STATUS,buildCommandWithYes,outputAgentError,withGlobalFlags}from"./chunk-WVUD3JPC.js";import{getFlagsSpecification,getGlobalFlagsFromArgs}from"./chunk-ROOWZCAB.js";import{getCommandName,getCommandNamePlain}from"./chunk-FI772UVH.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";async function requireProjectContext(client,command,projectName){let link=await resolveProjectContext({client,projectNameOrId:projectName});if(link.status==="error")return link.exitCode;if(link.status==="not_linked"){if(client.nonInteractive)if(command==="redirects"){let linkCmd=getCommandNamePlain("link");outputAgentError(client,{status:AGENT_STATUS.ERROR,reason:AGENT_REASON.NOT_LINKED,message:`Your codebase isn't linked to a project on Vercel. Run ${linkCmd} to begin.`,next:[{command:linkCmd}]},1)}else{let flags=getGlobalFlagsFromArgs(client.argv.slice(2)),cmd=getCommandNamePlain(`link ${flags.join(" ")}`.trim());return outputAgentError(client,{status:AGENT_STATUS.ERROR,reason:AGENT_REASON.NOT_LINKED,userActionRequired:!0,message:`Your codebase is not linked to a Vercel project. Run link first, then retry ${command} commands.`,next:[{command:cmd,when:"to link this directory to a project"}]},1),1}return output_manager_default.error(`Your codebase isn't linked to a project on Vercel. Run ${getCommandName("link")} to begin.`),1}return client.config.currentTeam=link.org.type==="team"?link.org.id:void 0,link}function parseSubcommandArguments(argv,command){let flagsSpecification=getFlagsSpecification(command.options);return parseArguments(argv,flagsSpecification)}function validateRequiredArguments(args,required){for(let i=0;i<required.length;i++)if(!args[i])return`Missing required argument: ${required[i]}`;return null}var ROUTE_TYPE_LABELS={rewrite:"Rewrite",redirect:"Redirect",set_status:"Set Status",transform:"Transform"};function getRouteTypeLabel(rule){return rule.routeType?ROUTE_TYPE_LABELS[rule.routeType]??"-":"-"}var SRC_SYNTAX_LABELS={equals:"Exact Match","path-to-regexp":"Pattern",regex:"Regex"};function getSrcSyntaxLabel(rule){let syntax=rule.srcSyntax??"regex";return SRC_SYNTAX_LABELS[syntax]}function isTargetTransform(transform){return"target"in transform}var import_chalk=__toESM(require_source(),1);function withGlobalFlags2(client,commandTemplate){return withGlobalFlags(client,commandTemplate,{preserveProject:!0})}function shellQuoteRouteIdentifierForSuggestion(identifier){return identifier.includes(" ")?identifier.includes("'")?identifier.includes('"')?`"${identifier.replace(/"/g,'\\"')}"`:`"${identifier}"`:`'${identifier}'`:identifier}async function parseSubcommandArgs(argv,command,client){let parsedArgs;try{parsedArgs=parseSubcommandArguments(argv,command)}catch(err){if(client?.nonInteractive){let rawMessage=err instanceof Error?err.message:String(err),flags=getGlobalFlagsFromArgs(client.argv.slice(2),{preserveProject:!0}),message=rawMessage,next=[{command:getCommandNamePlain(`routes ${command.name} ${flags.join(" ")}`.trim()),when:"fix flags and retry"}],aiIdx=argv.indexOf("--ai");return(aiIdx!==-1&&(aiIdx===argv.length-1||argv[aiIdx+1]!==void 0&&argv[aiIdx+1].startsWith("-"))||/option requires argument.*--ai|--ai.*requires argument/i.test(rawMessage))&&(command.name==="add"||command.name==="edit")&&(message=command.name==="add"?'--ai requires a description. Example: routes add --ai <description> --yes --non-interactive. Replace <description> with your text; use shell quotes if it contains spaces (e.g. --ai "Redirect /old to /new").':"--ai requires a description. Example: routes edit <name-or-id> --ai <description> --yes --non-interactive. Replace placeholders; use shell quotes for <description> if it contains spaces.",next=[{command:withGlobalFlags2(client,command.name==="add"?"routes add --ai <description> --yes":"routes edit <name-or-id> --ai <description> --yes"),when:"replace <description> with your text (quote it in the shell if it contains spaces), then run"},{command:getCommandNamePlain(`routes ${command.name} --help ${flags.join(" ")}`.trim()),when:"see all flags"}]),outputAgentError(client,{status:AGENT_STATUS.ERROR,reason:AGENT_REASON.INVALID_ARGUMENTS,message,next},2),2}return printError(err),2}return parsedArgs}async function confirmAction(client,skipConfirmation,message,details){return skipConfirmation?!0:client.nonInteractive?(outputAgentError(client,{status:AGENT_STATUS.ERROR,reason:AGENT_REASON.CONFIRMATION_REQUIRED,message:`${message} Re-run with --yes to confirm.`,next:[{command:buildCommandWithYes(client.argv),when:"re-run with --yes to confirm"}]}),process.exit(1),!1):(details&&output_manager_default.print(` ${details}
8
8
  `),await client.input.confirm(message,!1))}function formatCondition(condition){let parts=[import_chalk.default.gray(`[${condition.type}]`)];if(condition.key&&parts.push(import_chalk.default.cyan(condition.key)),condition.value!==void 0){let formatted=typeof condition.value=="string"?condition.value:JSON.stringify(condition.value);parts.push(condition.key?`= ${formatted}`:formatted)}return parts.join(" ")}var TRANSFORM_TYPE_LABELS={"request.headers":"Request Header","request.query":"Request Query","response.headers":"Response Header","request.path":"Request Path"},TRANSFORM_OP_LABELS={set:"set",append:"append",delete:"delete"};function formatTransform(transform,includeType=!0){let opLabel=TRANSFORM_OP_LABELS[transform.op]??transform.op,key=isTargetTransform(transform)?typeof transform.target.key=="string"?transform.target.key:JSON.stringify(transform.target.key):"path",parts=[];if(includeType){let typeLabel=TRANSFORM_TYPE_LABELS[transform.type]??transform.type;parts.push(import_chalk.default.gray(`[${typeLabel}]`))}if(parts.push(import_chalk.default.yellow(opLabel),import_chalk.default.cyan(key)),transform.args!==void 0&&transform.op!=="delete"){let argsStr=Array.isArray(transform.args)?transform.args.join(", "):transform.args;parts.push(`= ${argsStr}`)}return parts.join(" ")}function parsePosition(position){if(position==="start")return{placement:"start"};if(position==="end")return{placement:"end"};if(position.startsWith("after:")){let referenceId=position.slice(6);if(!referenceId)throw new Error('Position "after:" requires a route ID');return{placement:"after",referenceId}}if(position.startsWith("before:")){let referenceId=position.slice(7);if(!referenceId)throw new Error('Position "before:" requires a route ID');return{placement:"before",referenceId}}throw new Error(`Invalid position: "${position}". Use: start, end, after:<id>, or before:<id>`)}async function offerAutoPromote(client,projectId,version,hadExistingStagingVersion,opts){let{default:updateRouteVersion}=await import("./update-route-version-XZAFPQJC.js"),{default:stamp}=await import("./stamp-OX4YO3KY.js");if(output_manager_default.print(`
9
9
  ${import_chalk.default.gray(`This change is staged. Run ${import_chalk.default.cyan(withGlobalFlags2(client,"routes publish"))} to make it live, or ${import_chalk.default.cyan(withGlobalFlags2(client,"routes discard-staging"))} to undo.`)}
10
10
  `),!hadExistingStagingVersion&&!opts.skipPrompts){if(output_manager_default.print(`
@@ -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{require_format}from"./chunk-WRILLB46.js";import{events_default,require_jsonlines}from"./chunk-WW3VUXRV.js";import{CommandTimeout}from"./chunk-JRU6AGXG.js";import{require_ms}from"./chunk-QTKJC2O5.js";import{toNodeReadable}from"./chunk-MY4MONOH.js";import{require_strip_ansi}from"./chunk-OSCCYU74.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__commonJS,__require,__toESM}from"./chunk-6L236MNA.js";var require_split2=__commonJS({"../../node_modules/.pnpm/split2@4.2.0/node_modules/split2/index.js"(exports,module){"use strict";var{Transform}=__require("stream"),{StringDecoder}=__require("string_decoder"),kLast=Symbol("last"),kDecoder=Symbol("decoder");function transform(chunk,enc,cb){let list;if(this.overflow){if(list=this[kDecoder].write(chunk).split(this.matcher),list.length===1)return cb();list.shift(),this.overflow=!1}else this[kLast]+=this[kDecoder].write(chunk),list=this[kLast].split(this.matcher);this[kLast]=list.pop();for(let i=0;i<list.length;i++)try{push(this,this.mapper(list[i]))}catch(error){return cb(error)}if(this.overflow=this[kLast].length>this.maxLength,this.overflow&&!this.skipOverflow){cb(new Error("maximum buffer reached"));return}cb()}function flush(cb){if(this[kLast]+=this[kDecoder].end(),this[kLast])try{push(this,this.mapper(this[kLast]))}catch(error){return cb(error)}cb()}function push(self,val){val!==void 0&&self.push(val)}function noop(incoming){return incoming}function split2(matcher,mapper,options){switch(matcher=matcher||/\r?\n/,mapper=mapper||noop,options=options||{},arguments.length){case 1:typeof matcher=="function"?(mapper=matcher,matcher=/\r?\n/):typeof matcher=="object"&&!(matcher instanceof RegExp)&&!matcher[Symbol.split]&&(options=matcher,matcher=/\r?\n/);break;case 2:typeof matcher=="function"?(options=mapper,mapper=matcher,matcher=/\r?\n/):typeof mapper=="object"&&(options=mapper,mapper=noop)}options=Object.assign({},options),options.autoDestroy=!0,options.transform=transform,options.flush=flush,options.readableObjectMode=!0;let stream=new Transform(options);return stream[kLast]="",stream[kDecoder]=new StringDecoder("utf8"),stream.matcher=matcher,stream.mapper=mapper,stream.maxLength=options.maxLength,stream.skipOverflow=options.skipOverflow||!1,stream.overflow=!1,stream._destroy=function(err,cb){this._writableState.errorEmitted=!1,cb(err)},stream}module.exports=split2}});var import_chalk=__toESM(require_source(),1),import_format=__toESM(require_format(),1),import_ms=__toESM(require_ms(),1),import_jsonlines=__toESM(require_jsonlines(),1),import_split2=__toESM(require_split2(),1);import{URLSearchParams}from"url";var import_strip_ansi=__toESM(require_strip_ansi(),1);function displayBuildLogs(client,deployment,follow=!0,onAliasAssigned){let abortController=new AbortController;return{promise:events_default(client,deployment.id,{mode:"logs",onEvent:event=>printBuildLog(event,output_manager_default.print),onAliasAssigned,quiet:!1,findOpts:{direction:"forward",follow}},abortController),abortController}}function collectBuildLogs(client,deployment,follow=!0){let logs=[],abortController=new AbortController;return{promise:events_default(client,deployment.id,{mode:"logs",onEvent:event=>{event.created&&logs.push(event)},quiet:!0,findOpts:{direction:"forward",follow}},abortController).then(()=>logs),abortController}}async function displayBuildLogsUntilFinalError(client,deployment,error){let abortController=new AbortController;return events_default(client,deployment.id,{mode:"logs",onEvent:event=>{printBuildLog(event,output_manager_default.print),event.level==="error"&&event.text?.includes(error)&&abortController.abort()},quiet:!1,findOpts:{direction:"forward",follow:!0}},abortController)}var runtimeLogSpinnerMessage="waiting for new logs...";async function displayRuntimeLogs(client,options,abortController){let{log,debug,print,spinner,stopSpinner,warn}=output_manager_default,{projectId,deploymentId,parse}=options,query=new URLSearchParams({format:"lines"}),url=`/v1/projects/${projectId}/deployments/${deploymentId}/runtime-logs?${query}`;spinner(runtimeLogSpinnerMessage);let timeout=setTimeout(()=>{abortController.abort(),warn(`${import_chalk.default.bold(`Command automatically interrupted after ${CommandTimeout}.`)}
7
+ import{require_format}from"./chunk-WRILLB46.js";import{events_default,require_jsonlines}from"./chunk-2KCAQTPM.js";import{CommandTimeout}from"./chunk-TATIUO4V.js";import{require_ms}from"./chunk-QTKJC2O5.js";import{toNodeReadable}from"./chunk-MY4MONOH.js";import{require_strip_ansi}from"./chunk-OSCCYU74.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__commonJS,__require,__toESM}from"./chunk-6L236MNA.js";var require_split2=__commonJS({"../../node_modules/.pnpm/split2@4.2.0/node_modules/split2/index.js"(exports,module){"use strict";var{Transform}=__require("stream"),{StringDecoder}=__require("string_decoder"),kLast=Symbol("last"),kDecoder=Symbol("decoder");function transform(chunk,enc,cb){let list;if(this.overflow){if(list=this[kDecoder].write(chunk).split(this.matcher),list.length===1)return cb();list.shift(),this.overflow=!1}else this[kLast]+=this[kDecoder].write(chunk),list=this[kLast].split(this.matcher);this[kLast]=list.pop();for(let i=0;i<list.length;i++)try{push(this,this.mapper(list[i]))}catch(error){return cb(error)}if(this.overflow=this[kLast].length>this.maxLength,this.overflow&&!this.skipOverflow){cb(new Error("maximum buffer reached"));return}cb()}function flush(cb){if(this[kLast]+=this[kDecoder].end(),this[kLast])try{push(this,this.mapper(this[kLast]))}catch(error){return cb(error)}cb()}function push(self,val){val!==void 0&&self.push(val)}function noop(incoming){return incoming}function split2(matcher,mapper,options){switch(matcher=matcher||/\r?\n/,mapper=mapper||noop,options=options||{},arguments.length){case 1:typeof matcher=="function"?(mapper=matcher,matcher=/\r?\n/):typeof matcher=="object"&&!(matcher instanceof RegExp)&&!matcher[Symbol.split]&&(options=matcher,matcher=/\r?\n/);break;case 2:typeof matcher=="function"?(options=mapper,mapper=matcher,matcher=/\r?\n/):typeof mapper=="object"&&(options=mapper,mapper=noop)}options=Object.assign({},options),options.autoDestroy=!0,options.transform=transform,options.flush=flush,options.readableObjectMode=!0;let stream=new Transform(options);return stream[kLast]="",stream[kDecoder]=new StringDecoder("utf8"),stream.matcher=matcher,stream.mapper=mapper,stream.maxLength=options.maxLength,stream.skipOverflow=options.skipOverflow||!1,stream.overflow=!1,stream._destroy=function(err,cb){this._writableState.errorEmitted=!1,cb(err)},stream}module.exports=split2}});var import_chalk=__toESM(require_source(),1),import_format=__toESM(require_format(),1),import_ms=__toESM(require_ms(),1),import_jsonlines=__toESM(require_jsonlines(),1),import_split2=__toESM(require_split2(),1);import{URLSearchParams}from"url";var import_strip_ansi=__toESM(require_strip_ansi(),1);function displayBuildLogs(client,deployment,follow=!0,onAliasAssigned){let abortController=new AbortController;return{promise:events_default(client,deployment.id,{mode:"logs",onEvent:event=>printBuildLog(event,output_manager_default.print),onAliasAssigned,quiet:!1,findOpts:{direction:"forward",follow}},abortController),abortController}}function collectBuildLogs(client,deployment,follow=!0){let logs=[],abortController=new AbortController;return{promise:events_default(client,deployment.id,{mode:"logs",onEvent:event=>{event.created&&logs.push(event)},quiet:!0,findOpts:{direction:"forward",follow}},abortController).then(()=>logs),abortController}}async function displayBuildLogsUntilFinalError(client,deployment,error){let abortController=new AbortController;return events_default(client,deployment.id,{mode:"logs",onEvent:event=>{printBuildLog(event,output_manager_default.print),event.level==="error"&&event.text?.includes(error)&&abortController.abort()},quiet:!1,findOpts:{direction:"forward",follow:!0}},abortController)}var runtimeLogSpinnerMessage="waiting for new logs...";async function displayRuntimeLogs(client,options,abortController){let{log,debug,print,spinner,stopSpinner,warn}=output_manager_default,{projectId,deploymentId,parse}=options,query=new URLSearchParams({format:"lines"}),url=`/v1/projects/${projectId}/deployments/${deploymentId}/runtime-logs?${query}`;spinner(runtimeLogSpinnerMessage);let timeout=setTimeout(()=>{abortController.abort(),warn(`${import_chalk.default.bold(`Command automatically interrupted after ${CommandTimeout}.`)}
8
8
  `)},(0,import_ms.default)(CommandTimeout)),response=await client.fetch(url,{json:!1,signal:abortController.signal,retry:{retries:3,onRetry:err=>{if(log(`Runtime logs error: ${err.message}`),!(err instanceof Error&&err.name==="AbortError"))throw err}}});return new Promise((resolve,reject)=>{let readable=toNodeReadable(response.body),stream=readable.pipe(parse?import_jsonlines.default.parse():(0,import_split2.default)()),finished=!1,errored=!1;function finish(err){finished||(clearTimeout(timeout),stopSpinner(),finished=!0,err?reject(err):resolve(abortController.signal.aborted?1:0))}let handleData=data=>{let log2=parse?data:JSON.parse(data);if(stopSpinner(),isRuntimeLimitDelimiter(log2)){abortController.abort(),warn(`${import_chalk.default.bold(log2.message)}
9
9
  `);return}parse?prettyPrintLogline(log2,print):printRawLogLine(data,client),spinner(runtimeLogSpinnerMessage)},handleError=err=>{if(!(finished||errored)){if(err.name==="AbortError"){finish();return}stream.destroy(),errored=!0,debug(`Runtime logs stream error: ${err.message??err}`),setTimeout(()=>{abortController.signal.aborted||displayRuntimeLogs(client,options,abortController).then(resolve,reject)},2e3)}};stream.on("end",finish),stream.on("data",handleData),stream.on("error",handleError),readable.on("error",handleError)})}function printBuildLog(log,print){if(!log.created)return;let date=new Date(log.created).toISOString(),cleanText=parseLogLines(log).join(`
10
10
  `);for(let line of colorize(cleanText,log).split(`
@@ -0,0 +1,9 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
3
+ import { dirname as __dirname_ } from 'node:path';
4
+ const require = __createRequire(import.meta.url);
5
+ const __filename = __fileURLToPath(import.meta.url);
6
+ const __dirname = __dirname_(__filename);
7
+ import{emitAlertsScopeError,resolveAlertsScope}from"./chunk-VUCFX2G4.js";import{getExitCodeForErrorCode,handleValidationError,validateAllProjectMutualExclusivity}from"./chunk-J4YZKLVO.js";import{isJSONObject}from"./chunk-MJRZSYU2.js";import{getScope}from"./chunk-DBDWXNAR.js";import{getProjectByNameOrId}from"./chunk-LOD56FYJ.js";import{AGENT_REASON,buildCommandWithGlobalFlags,getExitCodeForReason,outputAgentError}from"./chunk-WVUD3JPC.js";import{ProjectNotFound,isAPIError}from"./chunk-RINZXCDJ.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";async function resolveRulesTeam(client,jsonOutput){let{team}=await getScope(client,{resolveLocalScope:!0});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:"Alert rules 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="alerts rules 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,"alerts rules --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}import{readFileSync}from"fs";import{resolve}from"path";function rulesCollectionPath(teamId,options={}){let query=new URLSearchParams({teamId});return options.limit!==void 0&&query.set("limit",String(options.limit)),options.cursor&&query.set("cursor",options.cursor),options.projectId&&query.set("projectId",options.projectId),options.type&&query.set("type",options.type),`/alerts/v3/alert-rules?${query.toString()}`}function rulesItemPath(teamId,ruleId){let query=new URLSearchParams({teamId});return`/alerts/v3/alert-rules/${encodeURIComponent(ruleId)}?${query.toString()}`}function ruleNotificationsPath(teamId,ruleId){let query=new URLSearchParams({teamId});return`/alerts/v3/alert-rules/${encodeURIComponent(ruleId)}/notifications?${query.toString()}`}function rulesNotificationsPath(teamId,options={}){let query=new URLSearchParams({teamId});return options.limit!==void 0&&query.set("limit",String(options.limit)),options.cursor&&query.set("cursor",options.cursor),`/alerts/v3/alert-rules/notifications?${query.toString()}`}function rulesNotificationLinksPath(teamId,ruleId){let query=new URLSearchParams({teamId});return`/alerts/v3/alert-rules/${encodeURIComponent(ruleId)}/notifications/links?${query.toString()}`}function rulesSchemaPath(teamId,type){let query=new URLSearchParams({teamId});return type&&query.set("type",type),`/alerts/v3/alert-rules/schema?${query.toString()}`}async function fetchRule(client,scope,ruleId){return(await client.fetch(rulesItemPath(scope.teamId,ruleId))).rule}function getIssues(error){return Array.isArray(error.issues)?error.issues.filter(issue=>isJSONObject(issue)&&typeof issue.path=="string"&&typeof issue.message=="string"):[]}function outputRulesError(client,jsonOutput,code,message,options={}){let issues=options.issues??[],issueSummary=issues.slice(0,5).map(issue=>`${issue.path||"body"}: ${issue.message}`).join("; "),exitCode=options.reason!==void 0?getExitCodeForReason(options.reason):getExitCodeForErrorCode(code);return outputAgentError(client,{status:"error",reason:options.reason??AGENT_REASON.INVALID_ARGUMENTS,message,hint:options.hint??(issueSummary||void 0)},exitCode),jsonOutput?client.stdout.write(`${JSON.stringify({error:{code,message,...issues.length?{issues}:{}}},null,2)}
8
+ `):output_manager_default.fatal([message,...issues.map(issue=>` ${issue.path}: ${issue.message}`)].join(`
9
+ `)),exitCode}function handleRulesApiError(client,err,jsonOutput){let message=err.status===401?"You do not have access to alert rules in this team. Ensure your role can manage Alert Rules, or pass --token and --scope.":err.status===403?err.serverMessage||"You do not have permission to manage alert rules in this team.":err.status>=500?`The alert rules endpoint failed (${err.status}). Re-run with --debug and share the x-vercel-id from the failed request.`:err.serverMessage||`API error (${err.status}).`;return outputRulesError(client,jsonOutput,err.code||"API_ERROR",message,{reason:err.status===401?"not_authorized":err.status===403?"forbidden":err.status===404?AGENT_REASON.NOT_FOUND:err.status===429?"rate_limited":AGENT_REASON.API_ERROR,issues:getIssues(err),hint:err.status===401||err.status===403?"Confirm the team with `vercel whoami`; use --scope <team-slug> if the rule belongs to another team.":void 0})}var LEGACY_BODY_FIELDS=["alertTypes","customAlert","queryJsonString"];function readRuleBody(client,bodyPath,jsonOutput){let raw;try{raw=readFileSync(resolve(client.cwd,bodyPath),"utf8")}catch{return outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS",`Could not read --body file: ${bodyPath}`)}let parsed;try{parsed=JSON.parse(raw)}catch{return outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS","Invalid JSON in --body file.")}return isJSONObject(parsed)?LEGACY_BODY_FIELDS.some(field=>Object.hasOwn(parsed,field))?outputRulesError(client,jsonOutput,"LEGACY_ALERT_RULE_BODY","This body uses the previous alert-rules shape. Rewrite it using the current schema.",{hint:"Run `vercel alerts rules schema --type built-in` for examples."}):parsed:outputRulesError(client,jsonOutput,"INVALID_ARGUMENTS","The --body file must contain a JSON object.")}function getBodyType(body){return body.type==="built-in"||body.type==="custom"?body.type:void 0}function emitRulesArgParseError(client,err,recoverWithProjectFlag){let message=err instanceof Error?err.message:String(err),projectFlagMissingArg=message.includes("--project")&&message.includes("requires argument");outputAgentError(client,{status:"error",reason:AGENT_REASON.INVALID_ARGUMENTS,message:projectFlagMissingArg?"`--project` requires a project name or id (for example `--project my-app`).":message,next:[{command:buildCommandWithGlobalFlags(client.argv,projectFlagMissingArg?recoverWithProjectFlag:"alerts rules --help"),when:projectFlagMissingArg?"Retry with a project name or id":"See valid `alerts rules` subcommands"}]},2)}export{resolveRulesTeam,resolveRulesProject,parseRulesFlagsAndScope,rulesCollectionPath,rulesItemPath,ruleNotificationsPath,rulesNotificationsPath,rulesNotificationLinksPath,rulesSchemaPath,fetchRule,outputRulesError,handleRulesApiError,readRuleBody,getBodyType,emitRulesArgParseError};
@@ -5,4 +5,4 @@ const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
7
  import{require_ms}from"./chunk-QTKJC2O5.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{__toESM}from"./chunk-6L236MNA.js";var import_ms=__toESM(require_ms(),1);function parseTimeFlag(input){let milliseconds=(0,import_ms.default)(input);if(milliseconds!==void 0)return new Date(Date.now()-milliseconds);let date=new Date(input);if(isNaN(date.getTime()))throw new Error(`Invalid time format "${input}". Use relative (1h, 30m, 2d, 1w) or ISO 8601 datetime.`);return date}function resolveTimeRange(since="1h",until){let startTime=parseTimeFlag(since),endTime=until?parseTimeFlag(until):new Date;return{startTime,endTime}}function validateAllProjectMutualExclusivity(all,project){return all&&project?{valid:!1,code:"MUTUAL_EXCLUSIVITY",message:"Cannot specify both --all and --project. Use one or the other."}:{valid:!0}}function validateTimeBound(input){if(!input)return{valid:!0,value:void 0};try{return{valid:!0,value:parseTimeFlag(input)}}catch(err){return{valid:!1,code:"INVALID_TIME",message:err.message}}}function validateTimeOrder(since,until){return since&&until&&since.getTime()>until.getTime()?{valid:!1,code:"INVALID_TIME_RANGE",message:"`--since` must be earlier than `--until`."}:{valid:!0}}function normalizeRepeatableStringFilters(filters){if(!filters||filters.length===0)return[];let normalized=filters.flatMap(filter=>filter.split(",")).map(filter=>filter.trim()).filter(Boolean);return[...new Set(normalized)]}function validateIntegerRangeWithDefault(value,opts){return value===void 0?{valid:!0,value:opts.defaultValue}:Number.isNaN(value)?{valid:!1,code:"INVALID_LIMIT",message:`Please provide a number for flag \`${opts.flag}\`.`}:!Number.isInteger(value)||value<opts.min||value>opts.max?{valid:!1,code:"INVALID_LIMIT",message:`\`${opts.flag}\` must be an integer between ${opts.min} and ${opts.max}.`}:{valid:!0,value}}function validateOptionalIntegerRange(value,opts){return value===void 0?{valid:!0,value:void 0}:Number.isNaN(value)?{valid:!1,code:opts.code||"INVALID_LIMIT",message:`Please provide a number for flag \`${opts.flag}\`.`}:!Number.isInteger(value)||value<opts.min||value>opts.max?{valid:!1,code:opts.code||"INVALID_LIMIT",message:`\`${opts.flag}\` must be an integer between ${opts.min} and ${opts.max}.`}:{valid:!0,value}}function formatJsonError(code,message){return`${JSON.stringify({error:{code,message}},null,2)}
8
- `}function writeJsonError(client,code,message){client.stdout.write(formatJsonError(code,message))}function outputError(client,jsonOutput,code,message){return jsonOutput?writeJsonError(client,code,message):output_manager_default.error(message),1}function handleValidationError(result,jsonOutput,client){return outputError(client,jsonOutput,result.code,result.message)}export{parseTimeFlag,resolveTimeRange,validateAllProjectMutualExclusivity,validateTimeBound,validateTimeOrder,normalizeRepeatableStringFilters,validateIntegerRangeWithDefault,validateOptionalIntegerRange,writeJsonError,outputError,handleValidationError};
8
+ `}function writeJsonError(client,code,message){client.stdout.write(formatJsonError(code,message))}var USAGE_ERROR_CODES=new Set(["CONFLICTING_CONTENT","INVALID_AGGREGATION","INVALID_ARGUMENTS","INVALID_ATTACHMENT","INVALID_GRANULARITY","INVALID_LIMIT","INVALID_RULE_TYPE","INVALID_STATUS","INVALID_THREAD","INVALID_TIME","INVALID_TIME_RANGE","MESSAGE_WITH_MULTIPLE_THREADS","MISSING_ARGUMENT","MISSING_ARGUMENTS","MISSING_CONTENT","MISSING_FLAG","MISSING_THREAD","MUTUAL_EXCLUSIVITY"]);function getExitCodeForErrorCode(code){return USAGE_ERROR_CODES.has(code)?2:1}function outputError(client,jsonOutput,code,message){return jsonOutput?writeJsonError(client,code,message):output_manager_default.error(message),getExitCodeForErrorCode(code)}function handleValidationError(result,jsonOutput,client){return outputError(client,jsonOutput,result.code,result.message)}export{parseTimeFlag,resolveTimeRange,validateAllProjectMutualExclusivity,validateTimeBound,validateTimeOrder,normalizeRepeatableStringFilters,validateIntegerRangeWithDefault,validateOptionalIntegerRange,writeJsonError,getExitCodeForErrorCode,outputError,handleValidationError};
@@ -4,6 +4,6 @@ import { dirname as __dirname_ } from 'node:path';
4
4
  const require = __createRequire(import.meta.url);
5
5
  const __filename = __fileURLToPath(import.meta.url);
6
6
  const __dirname = __dirname_(__filename);
7
- import{buildCorrectedCommand,isArgumentError}from"./chunk-LCWCTL6L.js";import{getErrorRecovery,shouldEmitNonInteractiveCommandError,trackAgentError,writeAgentError}from"./chunk-5VWK73R6.js";import{parseRetryAfterHeaderAsMillis,require_bytes}from"./chunk-RINZXCDJ.js";import{getCommandName}from"./chunk-FI772UVH.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{pkg_default}from"./chunk-AVSPFBLM.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";var import_chalk=__toESM(require_source(),1);var import_bytes=__toESM(require_bytes(),1);async function responseError(res,fallbackMessage=null,parsedBody={}){let message="",bodyError;if(res.status>=400&&res.status<500){let body;try{body=await res.json()}catch{body=parsedBody}bodyError=body.error||body.err||{},message=bodyError.message}message||(message=fallbackMessage===null?"Response Error":fallbackMessage);let err=new Error(`${message} (${res.status})`);if(err.status=res.status,err.serverMessage=message,bodyError)for(let field of Object.keys(bodyError))field!=="message"&&(err[field]=bodyError[field]);if(res.status===429||res.status===503){let parsed=parseRetryAfterHeaderAsMillis(res.headers.get("Retry-After"));err.retryAfterMs=parsed??(res.status===429?0:void 0)}return err}var MAX_SERIALIZED_ERROR_DEPTH=5;function isPlainObject(value){let proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function toJsonSafe(value,ancestors,depth){if(typeof value=="bigint")return value.toString();if(!(typeof value=="function"||typeof value=="symbol")){if(value===null||typeof value!="object")return value;if(ancestors.has(value))return"[Circular]";if(depth>=MAX_SERIALIZED_ERROR_DEPTH)return"[Truncated]";if(value instanceof Error)return serializeError(value,ancestors,depth+1);if(!Array.isArray(value)&&!isPlainObject(value))return`[${value.constructor?.name||"Object"}]`;ancestors.add(value);try{if(Array.isArray(value))return value.map(item=>toJsonSafe(item,ancestors,depth+1));let copy={};for(let[key,child]of Object.entries(value))copy[key]=toJsonSafe(child,ancestors,depth+1);return copy}finally{ancestors.delete(value)}}}function serializeError(err,ancestors,depth){ancestors.add(err);try{let enumerable={name:err.name};for(let key of Object.getOwnPropertyNames(err))enumerable[key]=toJsonSafe(err[key],ancestors,depth);return enumerable}finally{ancestors.delete(err)}}function toEnumerableError(err){return err===null||typeof err!="object"?{name:"Error",message:String(err)}:serializeError(err,new WeakSet,0)}function printError(error2,client){typeof error2=="string"&&(error2=new Error(error2));let apiError=error2,{message,stack,status,code,sizeLimit}=apiError,argumentError=isArgumentError(error2)?error2:void 0,suggestion=argumentError?.suggestedOption&&argumentError.invalidOption,correction=suggestion&&client&&argumentError?buildCorrectedCommand(client.argv,argumentError.invalidOption,argumentError.suggestedOption,argumentError.flagsSpecification):void 0,recovery=getErrorRecovery(apiError,client),reason=status===403?"forbidden":status===402?"payment_required":status===401?"not_authorized":status===429?"rate_limited":argumentError?"invalid_arguments":"api_error",hint=argumentError?.allowedOptions?`Vercel CLI ${pkg_default.version} accepts: ${argumentError.allowedOptions.join(", ")}.${suggestion?` Did you mean ${argumentError.suggestedOption}?`:""}`:recovery.hint;if(client&&(status||argumentError?.allowedOptions)){let payload={...recovery,status:"error",reason,message:apiError.serverMessage||message,hint,...argumentError?.allowedOptions&&{allowedOptions:argumentError.allowedOptions,suggestedOption:argumentError.suggestedOption,cliVersion:pkg_default.version},...correction&&{next:[{command:correction,when:correction.includes("<")?"Replace placeholders with the intended values, then run the corrected command":"Run the corrected command"}]}};if(shouldEmitNonInteractiveCommandError(client)){output_manager_default.stopSpinner(),writeAgentError(client,payload);return}trackAgentError(client,payload)}if(hint){output_manager_default.stopSpinner(),output_manager_default.fatal(apiError.serverMessage||message||"The request failed."),output_manager_default.print(` ${hint}
7
+ import{buildCorrectedCommand,isArgumentError}from"./chunk-PTUZ7ATN.js";import{getErrorRecovery,shouldEmitNonInteractiveCommandError,trackAgentError,writeAgentError}from"./chunk-WVUD3JPC.js";import{parseRetryAfterHeaderAsMillis,require_bytes}from"./chunk-RINZXCDJ.js";import{getCommandName}from"./chunk-FI772UVH.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{pkg_default}from"./chunk-AVSPFBLM.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";var import_chalk=__toESM(require_source(),1);var import_bytes=__toESM(require_bytes(),1);async function responseError(res,fallbackMessage=null,parsedBody={}){let message="",bodyError;if(res.status>=400&&res.status<500){let body;try{body=await res.json()}catch{body=parsedBody}bodyError=body.error||body.err||{},message=bodyError.message}message||(message=fallbackMessage===null?"Response Error":fallbackMessage);let err=new Error(`${message} (${res.status})`);if(err.status=res.status,err.serverMessage=message,bodyError)for(let field of Object.keys(bodyError))field!=="message"&&(err[field]=bodyError[field]);if(res.status===429||res.status===503){let parsed=parseRetryAfterHeaderAsMillis(res.headers.get("Retry-After"));err.retryAfterMs=parsed??(res.status===429?0:void 0)}return err}var MAX_SERIALIZED_ERROR_DEPTH=5;function isPlainObject(value){let proto=Object.getPrototypeOf(value);return proto===null||proto===Object.prototype}function toJsonSafe(value,ancestors,depth){if(typeof value=="bigint")return value.toString();if(!(typeof value=="function"||typeof value=="symbol")){if(value===null||typeof value!="object")return value;if(ancestors.has(value))return"[Circular]";if(depth>=MAX_SERIALIZED_ERROR_DEPTH)return"[Truncated]";if(value instanceof Error)return serializeError(value,ancestors,depth+1);if(!Array.isArray(value)&&!isPlainObject(value))return`[${value.constructor?.name||"Object"}]`;ancestors.add(value);try{if(Array.isArray(value))return value.map(item=>toJsonSafe(item,ancestors,depth+1));let copy={};for(let[key,child]of Object.entries(value))copy[key]=toJsonSafe(child,ancestors,depth+1);return copy}finally{ancestors.delete(value)}}}function serializeError(err,ancestors,depth){ancestors.add(err);try{let enumerable={name:err.name};for(let key of Object.getOwnPropertyNames(err))enumerable[key]=toJsonSafe(err[key],ancestors,depth);return enumerable}finally{ancestors.delete(err)}}function toEnumerableError(err){return err===null||typeof err!="object"?{name:"Error",message:String(err)}:serializeError(err,new WeakSet,0)}function printError(error2,client){typeof error2=="string"&&(error2=new Error(error2));let apiError=error2,{message,stack,status,code,sizeLimit}=apiError,argumentError=isArgumentError(error2)?error2:void 0,suggestion=argumentError?.suggestedOption&&argumentError.invalidOption,correction=suggestion&&client&&argumentError?buildCorrectedCommand(client.argv,argumentError.invalidOption,argumentError.suggestedOption,argumentError.flagsSpecification):void 0,recovery=getErrorRecovery(apiError,client),reason=status===403?"forbidden":status===402?"payment_required":status===401?"not_authorized":status===429?"rate_limited":argumentError?"invalid_arguments":"api_error",hint=argumentError?.allowedOptions?`Vercel CLI ${pkg_default.version} accepts: ${argumentError.allowedOptions.join(", ")}.${suggestion?` Did you mean ${argumentError.suggestedOption}?`:""}`:recovery.hint;if(client&&(status||argumentError?.allowedOptions)){let payload={...recovery,status:"error",reason,message:apiError.serverMessage||message,hint,...argumentError?.allowedOptions&&{allowedOptions:argumentError.allowedOptions,suggestedOption:argumentError.suggestedOption,cliVersion:pkg_default.version},...correction&&{next:[{command:correction,when:correction.includes("<")?"Replace placeholders with the intended values, then run the corrected command":"Run the corrected command"}]}};if(shouldEmitNonInteractiveCommandError(client)){output_manager_default.stopSpinner(),writeAgentError(client,payload);return}trackAgentError(client,payload)}if(hint){output_manager_default.stopSpinner(),output_manager_default.fatal(apiError.serverMessage||message||"The request failed."),output_manager_default.print(` ${hint}
8
8
  `),correction&&output_manager_default.print(` ${correction}
9
9
  `);return}output_manager_default.debug(`handling error: ${stack}`),message!=="User force closed the prompt with 0 null"&&(status===403?output_manager_default.error(message||`Authentication error. Run ${getCommandName("login")} to log-in again.`):status===429?output_manager_default.error(message):code==="size_limit_exceeded"?output_manager_default.error(`File size limit exceeded (${(0,import_bytes.default)(sizeLimit)})`):message?output_manager_default.prettyError(apiError):status===500?output_manager_default.error("Unexpected server error. Please retry."):code==="USER_ABORT"?output_manager_default.log("Canceled"):output_manager_default.error(`Unexpected error. Please try again later. (${message})`))}export{responseError,toEnumerableError,printError};
@@ -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{permissionsAggregateCommand}from"./chunk-2RQFMCPJ.js";import{tagsAggregateCommand}from"./chunk-NT67T6DL.js";import{imageAggregateCommand}from"./chunk-NESZV33T.js";import{formatOption,jsonOption,limitOption,projectOption,yesOption}from"./chunk-PV5YI2ZZ.js";import{packageName}from"./chunk-FI772UVH.js";var projectScopeOption={...projectOption,shorthand:"p",description:"Project name or ID (defaults to the linked project)."},nextOption={name:"next",shorthand:null,type:String,deprecated:!1,description:"Continue from a previous response",argument:"CURSOR"},cursorOption={name:"cursor",shorthand:"c",type:String,deprecated:!0,description:"Cursor from a previous page to continue listing from",argument:"STRING"},platformOption={name:"platform",shorthand:null,type:String,deprecated:!1,description:"Target platform for the build (defaults to linux/amd64).",argument:"PLATFORM"},pushOption={name:"push",shorthand:null,type:Boolean,deprecated:!1,description:"Push the image after building. With Docker this builds and pushes in one step (Buildx enables zstd compression); Podman and Buildah build, then push with zstd compression."},publicOption={name:"public",shorthand:null,type:String,deprecated:!1,description:"Set the repository visibility: `true` for public, `false` for private.",argument:"BOOLEAN",choices:["true","false"]},listSubcommand={name:"ls",aliases:["list"],description:"List container registry repositories for a project",arguments:[],options:[projectScopeOption,limitOption,nextOption,cursorOption,formatOption,jsonOption],examples:[{name:"List repositories in the linked project",value:`${packageName} vcr ls`},{name:"List repositories for a specific project as JSON",value:`${packageName} vcr ls --project my-app --json`}]},inspectSubcommand={name:"inspect",aliases:["get"],description:"Show details for a single repository",arguments:[{name:"repository",required:!0}],options:[projectScopeOption,formatOption,jsonOption],examples:[{name:"Inspect a repository by name",value:`${packageName} vcr inspect my-repository`}]},addSubcommand={name:"create",aliases:["add"],description:"Create a container registry repository",arguments:[{name:"name",required:!0}],options:[projectScopeOption,formatOption,jsonOption],examples:[{name:"Create a repository",value:`${packageName} vcr create my-repository`}]},configSubcommand={name:"config",aliases:[],description:"Configure a container registry repository, such as the repository's visibility",arguments:[{name:"repository",required:!0}],options:[publicOption,projectScopeOption,formatOption,jsonOption],examples:[{name:"Make a repository public",value:`${packageName} vcr config my-repository --public true`},{name:"Make a repository private",value:`${packageName} vcr config my-repository --public false`}]},removeSubcommand={name:"rm",aliases:["remove","delete"],description:"Delete a container registry repository",arguments:[{name:"repository",required:!0}],options:[projectScopeOption,yesOption,formatOption,jsonOption],examples:[{name:"Delete a repository",value:`${packageName} vcr rm my-repository`},{name:"Delete a repository without the confirmation prompt",value:`${packageName} vcr rm my-repository --yes`}]},loginSubcommand={name:"login",aliases:[],description:"Authenticate a container tool (docker, podman, or buildah) with the Vercel Container Registry",arguments:[{name:"engine",required:!0}],options:[projectScopeOption,formatOption,jsonOption],examples:[{name:"Log in with Docker",value:`${packageName} vcr login docker`},{name:"Log in with Podman",value:`${packageName} vcr login podman`},{name:"Log in with Buildah",value:`${packageName} vcr login buildah`},{name:"Log in for a specific project",value:`${packageName} vcr login docker --project my-app`}]},buildSubcommand={name:"build",aliases:[],description:"Build a container image tagged for the Vercel Container Registry by shelling out to your container tool (docker, podman, or buildah)",arguments:[{name:"engine",required:!0},{name:"path",required:!1},{name:"name",required:!1}],options:[projectScopeOption,platformOption,pushOption],examples:[{name:"Build the current directory into the linked project (repository defaults to the project name, tag to latest)",value:`${packageName} vcr build docker`},{name:"Build and push in one step (Docker Buildx enables zstd compression)",value:`${packageName} vcr build docker --push`},{name:"Build a specific context path with a repository and tag",value:`${packageName} vcr build docker ./app my-api:1.2.3`},{name:"Pass extra flags through to the container tool",value:`${packageName} vcr build docker . -- --no-cache --build-arg KEY=value`}]},pushSubcommand={name:"push",aliases:[],description:"Push a container image to the Vercel Container Registry by shelling out to your container tool (docker, podman, or buildah)",arguments:[{name:"engine",required:!0},{name:"name",required:!1}],options:[projectScopeOption],examples:[{name:"Push the linked project image (repository defaults to the project name, tag to latest)",value:`${packageName} vcr push docker`},{name:"Push a specific repository and tag",value:`${packageName} vcr push docker my-api:1.2.3`}]},vcrCommand={name:"vcr",aliases:[],description:"Manage Vercel Container Registry repositories and images (see `vcr image`).",arguments:[],subcommands:[listSubcommand,inspectSubcommand,addSubcommand,configSubcommand,removeSubcommand,loginSubcommand,buildSubcommand,pushSubcommand,tagsAggregateCommand,imageAggregateCommand,permissionsAggregateCommand],options:[],examples:[{name:"List repositories in the linked project",value:`${packageName} vcr ls`},{name:"Create a repository",value:`${packageName} vcr create my-app`},{name:"List images in a repository",value:`${packageName} vcr image ls my-app`}]};export{listSubcommand,inspectSubcommand,addSubcommand,configSubcommand,removeSubcommand,loginSubcommand,buildSubcommand,pushSubcommand,vcrCommand};
7
+ import{permissionsAggregateCommand}from"./chunk-54SEEVOA.js";import{tagsAggregateCommand}from"./chunk-3HO365U7.js";import{imageAggregateCommand}from"./chunk-WT73KR4Y.js";import{formatOption,jsonOption,limitOption,projectOption,yesOption}from"./chunk-ROOWZCAB.js";import{packageName}from"./chunk-FI772UVH.js";var projectScopeOption={...projectOption,shorthand:"p",description:"Project name or ID (defaults to the linked project)."},nextOption={name:"next",shorthand:null,type:String,deprecated:!1,description:"Continue from a previous response",argument:"CURSOR"},cursorOption={name:"cursor",shorthand:"c",type:String,deprecated:!0,description:"Cursor from a previous page to continue listing from",argument:"STRING"},platformOption={name:"platform",shorthand:null,type:String,deprecated:!1,description:"Target platform for the build (defaults to linux/amd64).",argument:"PLATFORM"},pushOption={name:"push",shorthand:null,type:Boolean,deprecated:!1,description:"Push the image after building. With Docker this builds and pushes in one step (Buildx enables zstd compression); Podman and Buildah build, then push with zstd compression."},publicOption={name:"public",shorthand:null,type:String,deprecated:!1,description:"Set the repository visibility: `true` for public, `false` for private.",argument:"BOOLEAN",choices:["true","false"]},listSubcommand={name:"ls",aliases:["list"],description:"List container registry repositories for a project",arguments:[],options:[projectScopeOption,limitOption,nextOption,cursorOption,formatOption,jsonOption],examples:[{name:"List repositories in the linked project",value:`${packageName} vcr ls`},{name:"List repositories for a specific project as JSON",value:`${packageName} vcr ls --project my-app --json`}]},inspectSubcommand={name:"inspect",aliases:["get"],description:"Show details for a single repository",arguments:[{name:"repository",required:!0}],options:[projectScopeOption,formatOption,jsonOption],examples:[{name:"Inspect a repository by name",value:`${packageName} vcr inspect my-repository`}]},addSubcommand={name:"create",aliases:["add"],description:"Create a container registry repository",arguments:[{name:"name",required:!0}],options:[projectScopeOption,formatOption,jsonOption],examples:[{name:"Create a repository",value:`${packageName} vcr create my-repository`}]},configSubcommand={name:"config",aliases:[],description:"Configure a container registry repository, such as the repository's visibility",arguments:[{name:"repository",required:!0}],options:[publicOption,projectScopeOption,formatOption,jsonOption],examples:[{name:"Make a repository public",value:`${packageName} vcr config my-repository --public true`},{name:"Make a repository private",value:`${packageName} vcr config my-repository --public false`}]},removeSubcommand={name:"rm",aliases:["remove","delete"],description:"Delete a container registry repository",arguments:[{name:"repository",required:!0}],options:[projectScopeOption,yesOption,formatOption,jsonOption],examples:[{name:"Delete a repository",value:`${packageName} vcr rm my-repository`},{name:"Delete a repository without the confirmation prompt",value:`${packageName} vcr rm my-repository --yes`}]},loginSubcommand={name:"login",aliases:[],description:"Authenticate a container tool (docker, podman, or buildah) with the Vercel Container Registry",arguments:[{name:"engine",required:!0}],options:[projectScopeOption,formatOption,jsonOption],examples:[{name:"Log in with Docker",value:`${packageName} vcr login docker`},{name:"Log in with Podman",value:`${packageName} vcr login podman`},{name:"Log in with Buildah",value:`${packageName} vcr login buildah`},{name:"Log in for a specific project",value:`${packageName} vcr login docker --project my-app`}]},buildSubcommand={name:"build",aliases:[],description:"Build a container image tagged for the Vercel Container Registry by shelling out to your container tool (docker, podman, or buildah)",arguments:[{name:"engine",required:!0},{name:"path",required:!1},{name:"name",required:!1}],options:[projectScopeOption,platformOption,pushOption],examples:[{name:"Build the current directory into the linked project (repository defaults to the project name, tag to latest)",value:`${packageName} vcr build docker`},{name:"Build and push in one step (Docker Buildx enables zstd compression)",value:`${packageName} vcr build docker --push`},{name:"Build a specific context path with a repository and tag",value:`${packageName} vcr build docker ./app my-api:1.2.3`},{name:"Pass extra flags through to the container tool",value:`${packageName} vcr build docker . -- --no-cache --build-arg KEY=value`}]},pushSubcommand={name:"push",aliases:[],description:"Push a container image to the Vercel Container Registry by shelling out to your container tool (docker, podman, or buildah)",arguments:[{name:"engine",required:!0},{name:"name",required:!1}],options:[projectScopeOption],examples:[{name:"Push the linked project image (repository defaults to the project name, tag to latest)",value:`${packageName} vcr push docker`},{name:"Push a specific repository and tag",value:`${packageName} vcr push docker my-api:1.2.3`}]},vcrCommand={name:"vcr",aliases:[],description:"Manage Vercel Container Registry repositories and images (see `vcr image`).",arguments:[],subcommands:[listSubcommand,inspectSubcommand,addSubcommand,configSubcommand,removeSubcommand,loginSubcommand,buildSubcommand,pushSubcommand,tagsAggregateCommand,imageAggregateCommand,permissionsAggregateCommand],options:[],examples:[{name:"List repositories in the linked project",value:`${packageName} vcr ls`},{name:"Create a repository",value:`${packageName} vcr create my-app`},{name:"List images in a repository",value:`${packageName} vcr image ls my-app`}]};export{listSubcommand,inspectSubcommand,addSubcommand,configSubcommand,removeSubcommand,loginSubcommand,buildSubcommand,pushSubcommand,vcrCommand};
@@ -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{readJSONFile}from"./chunk-K5WTLFS6.js";import{require_dist as require_dist2,validateConfig}from"./chunk-NXTK7VKL.js";import{require_dist2 as require_dist}from"./chunk-N4PVXHAJ.js";import{compileVercelConfig}from"./chunk-UWO3M2L2.js";import{CantParseJSONFile}from"./chunk-RINZXCDJ.js";import{require_build_utils}from"./chunk-EWWFNMPZ.js";import{__toESM}from"./chunk-6L236MNA.js";var import_fs_detectors=__toESM(require_dist(),1),import_service_topology=__toESM(require_dist2(),1);import{readFile,writeFile}from"fs/promises";import{basename,join as join2}from"path";import{parse as tomlParse,stringify as tomlStringify}from"smol-toml";var import_build_utils=__toESM(require_build_utils(),1);import{join}from"path";function createDetectEntrypoint(projectRoot){return async({workPath,framework})=>{let absWorkPath=(0,import_build_utils.normalizePath)(join(projectRoot,workPath)),builderName;if((0,import_build_utils.isPythonFramework)(framework))builderName="@vercel/python";else if((0,import_build_utils.isNodeBackendFramework)(framework))builderName="@vercel/backends";else if(framework==="go")builderName="@vercel/go";else if(framework==="rust")builderName="@vercel/rust";else return null;let detectEntrypoint=await loadBuilderDetectEntrypoint(builderName,projectRoot);return detectEntrypoint?detectEntrypoint(builderName==="@vercel/python"?{workPath:absWorkPath,framework}:{workPath:absWorkPath}):null}}async function loadBuilderDetectEntrypoint(name,projectRoot){let{importBuilders}=await import("./import-builders-EUOOFPHW.js"),loaded=(await importBuilders(new Set([name]),projectRoot)).get(name);if(!loaded)return;let detect=loaded.builder.detectEntrypoint;return typeof detect=="function"?detect:void 0}function getServicesConfiguration(config){let configuredServices=config?.services??config?.experimentalServicesV2??config?.experimentalServices,configuredServicesType=config?.services?"services":config?.experimentalServicesV2?"experimentalServicesV2":config?.experimentalServices?"experimentalServices":void 0;return{configuredServices,configuredServicesType}}async function loadVercelConfig(cwd){try{let{configPath}=await compileVercelConfig(cwd);if(!configPath)return null;let config=await readJSONFile(configPath);return config instanceof Error?null:config}catch{return null}}function isServicesEnvEnabled(){let value=process.env.VERCEL_USE_EXPERIMENTAL_SERVICES;return value==="1"||value?.toLowerCase()==="true"}async function isExperimentalServicesEnabled(cwd){let{configuredServices}=getServicesConfiguration(await loadVercelConfig(cwd));return isServicesEnvEnabled()||configuredServices!==void 0}async function tryDetectServices(cwd,config){config===void 0&&(config=await loadVercelConfig(cwd));let configuration=getServicesConfiguration(config);if(!isServicesEnvEnabled()&&!configuration.configuredServices)return null;let fs=new import_fs_detectors.LocalFileSystemDetector(cwd),result=await(0,import_service_topology.detectServices)({fs,configuredServices:configuration.configuredServices,configuredServicesType:configuration.configuredServicesType,detectEntrypoint:createDetectEntrypoint(cwd)});return result.errors.some(e=>e.code==="NO_SERVICES_CONFIGURED")?null:result}async function writeServicesConfig(cwd,config){let prepared=await prepareServicesConfigWrite(cwd,config);return await writeFile(prepared.configPath,prepared.content,"utf8"),{configFileName:basename(prepared.configPath)}}async function getServicesConfigWriteBlocker(cwd,config){try{return await prepareServicesConfigWrite(cwd,config),null}catch(error){return getServicesConfigWriteBlockerFromError(error)}}function toProjectServicesConfigPatch(config){let services={};for(let[name,svc]of Object.entries(config)){let buildCommand=svc.preDeployCommand&&svc.buildCommand?`${svc.buildCommand} && ${svc.preDeployCommand}`:svc.preDeployCommand||svc.buildCommand;services[name]={root:svc.root,...svc.framework?{framework:svc.framework}:{},...svc.entrypoint?{entrypoint:svc.entrypoint}:{},...buildCommand?{buildCommand}:{}}}let rewrites=(0,import_service_topology.generateServiceRewrites)(config);return{services,...rewrites.length>0?{rewrites}:{}}}async function prepareServicesConfigWrite(cwd,config){let compileResult=await compileVercelConfig(cwd),configPath=join2(cwd,"vercel.json");if(compileResult.sourceFile==="vercel.toml")return prepareTomlServicesConfigWrite(join2(cwd,"vercel.toml"),config);if(compileResult.wasCompiled)throw new Error(`Cannot automatically update ${compileResult.sourceFile??"the current Vercel config"}.`);let existingConfig={};if(compileResult.configPath&&basename(compileResult.configPath)==="vercel.json"){let result=await readJSONFile(configPath);if(result instanceof CantParseJSONFile)throw result;existingConfig=result??{}}let patch=toProjectServicesConfigPatch(config),nextConfig={...existingConfig,...patch,...patch.rewrites?{rewrites:[...existingConfig.rewrites??[],...patch.rewrites]}:{}},validationError=validateConfig(nextConfig);if(validationError)throw validationError;return{configPath,content:JSON.stringify(nextConfig,null,2)+`
7
+ import{readJSONFile}from"./chunk-FSHYI4ZE.js";import{require_dist as require_dist2,validateConfig}from"./chunk-EZU5U2PZ.js";import{require_dist2 as require_dist}from"./chunk-G3NHWIPJ.js";import{compileVercelConfig}from"./chunk-57NFMJ6O.js";import{CantParseJSONFile}from"./chunk-RINZXCDJ.js";import{require_build_utils}from"./chunk-EWWFNMPZ.js";import{__toESM}from"./chunk-6L236MNA.js";var import_fs_detectors=__toESM(require_dist(),1),import_service_topology=__toESM(require_dist2(),1);import{readFile,writeFile}from"fs/promises";import{basename,join as join2}from"path";import{parse as tomlParse,stringify as tomlStringify}from"smol-toml";var import_build_utils=__toESM(require_build_utils(),1);import{join}from"path";function createDetectEntrypoint(projectRoot){return async({workPath,framework})=>{let absWorkPath=(0,import_build_utils.normalizePath)(join(projectRoot,workPath)),builderName;if((0,import_build_utils.isPythonFramework)(framework))builderName="@vercel/python";else if((0,import_build_utils.isNodeBackendFramework)(framework))builderName="@vercel/backends";else if(framework==="go")builderName="@vercel/go";else if(framework==="rust")builderName="@vercel/rust";else return null;let detectEntrypoint=await loadBuilderDetectEntrypoint(builderName,projectRoot);return detectEntrypoint?detectEntrypoint(builderName==="@vercel/python"?{workPath:absWorkPath,framework}:{workPath:absWorkPath}):null}}async function loadBuilderDetectEntrypoint(name,projectRoot){let{importBuilders}=await import("./import-builders-JXIILQOI.js"),loaded=(await importBuilders(new Set([name]),projectRoot)).get(name);if(!loaded)return;let detect=loaded.builder.detectEntrypoint;return typeof detect=="function"?detect:void 0}function getServicesConfiguration(config){let configuredServices=config?.services??config?.experimentalServicesV2??config?.experimentalServices,configuredServicesType=config?.services?"services":config?.experimentalServicesV2?"experimentalServicesV2":config?.experimentalServices?"experimentalServices":void 0;return{configuredServices,configuredServicesType}}async function loadVercelConfig(cwd){try{let{configPath}=await compileVercelConfig(cwd);if(!configPath)return null;let config=await readJSONFile(configPath);return config instanceof Error?null:config}catch{return null}}function isServicesEnvEnabled(){let value=process.env.VERCEL_USE_EXPERIMENTAL_SERVICES;return value==="1"||value?.toLowerCase()==="true"}async function isExperimentalServicesEnabled(cwd){let{configuredServices}=getServicesConfiguration(await loadVercelConfig(cwd));return isServicesEnvEnabled()||configuredServices!==void 0}async function tryDetectServices(cwd,config){config===void 0&&(config=await loadVercelConfig(cwd));let configuration=getServicesConfiguration(config);if(!isServicesEnvEnabled()&&!configuration.configuredServices)return null;let fs=new import_fs_detectors.LocalFileSystemDetector(cwd),result=await(0,import_service_topology.detectServices)({fs,configuredServices:configuration.configuredServices,configuredServicesType:configuration.configuredServicesType,detectEntrypoint:createDetectEntrypoint(cwd)});return result.errors.some(e=>e.code==="NO_SERVICES_CONFIGURED")?null:result}async function writeServicesConfig(cwd,config){let prepared=await prepareServicesConfigWrite(cwd,config);return await writeFile(prepared.configPath,prepared.content,"utf8"),{configFileName:basename(prepared.configPath)}}async function getServicesConfigWriteBlocker(cwd,config){try{return await prepareServicesConfigWrite(cwd,config),null}catch(error){return getServicesConfigWriteBlockerFromError(error)}}function toProjectServicesConfigPatch(config){let services={};for(let[name,svc]of Object.entries(config)){let buildCommand=svc.preDeployCommand&&svc.buildCommand?`${svc.buildCommand} && ${svc.preDeployCommand}`:svc.preDeployCommand||svc.buildCommand;services[name]={root:svc.root,...svc.framework?{framework:svc.framework}:{},...svc.entrypoint?{entrypoint:svc.entrypoint}:{},...buildCommand?{buildCommand}:{}}}let rewrites=(0,import_service_topology.generateServiceRewrites)(config);return{services,...rewrites.length>0?{rewrites}:{}}}async function prepareServicesConfigWrite(cwd,config){let compileResult=await compileVercelConfig(cwd),configPath=join2(cwd,"vercel.json");if(compileResult.sourceFile==="vercel.toml")return prepareTomlServicesConfigWrite(join2(cwd,"vercel.toml"),config);if(compileResult.wasCompiled)throw new Error(`Cannot automatically update ${compileResult.sourceFile??"the current Vercel config"}.`);let existingConfig={};if(compileResult.configPath&&basename(compileResult.configPath)==="vercel.json"){let result=await readJSONFile(configPath);if(result instanceof CantParseJSONFile)throw result;existingConfig=result??{}}let patch=toProjectServicesConfigPatch(config),nextConfig={...existingConfig,...patch,...patch.rewrites?{rewrites:[...existingConfig.rewrites??[],...patch.rewrites]}:{}},validationError=validateConfig(nextConfig);if(validationError)throw validationError;return{configPath,content:JSON.stringify(nextConfig,null,2)+`
8
8
  `}}async function prepareTomlServicesConfigWrite(configPath,config){let patch=toProjectServicesConfigPatch(config),patchKeys=Object.keys(patch),existingContent;try{existingContent=await readFile(configPath,"utf8")}catch{existingContent=""}if(existingContent.trim()){let existingParsed=tomlParse(existingContent),overlapping=patchKeys.filter(key=>key in existingParsed);if(overlapping.length>0){let plural=overlapping.length>1,keyList=overlapping.map(k=>`"${k}"`).join(", ");throw new Error(`Cannot automatically update vercel.toml: key${plural?"s":""} ${keyList} already exist${plural?"":"s"}.`)}}let patchToml=tomlStringify(patch),content=existingContent.trim()?existingContent.trimEnd()+`
9
9
 
10
10
  `+patchToml+`
@@ -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{getGlobalPathConfig}from"./chunk-CQ3RAERR.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";var OPENAPI_URL="https://openapi.vercel.sh/",SSO_API_URL="https://vercel.com/sso-api",CACHE_FILE="openapi-spec.json",CACHE_TTL_MS=864e5,FETCH_TIMEOUT_MS=1e4,MAX_OPENAPI_SPEC_BYTES=52428800,VERCEL_CLI_ROOT_DISPLAY_KEY="__root__";async function readSpecResponse(response,url,maxBytes=52428800){let contentLength=response.headers.get("content-length");if(contentLength){let bytes=Number(contentLength);if(Number.isFinite(bytes)&&bytes>maxBytes)throw new Error(`OpenAPI spec from ${url} exceeds the ${maxBytes} byte limit.`)}if(!response.body)throw new Error(`OpenAPI spec from ${url} returned an empty response.`);let reader=response.body.getReader(),chunks=[],totalBytes=0;for(;;){let{done,value}=await reader.read();if(done)break;if(value){if(totalBytes+=value.byteLength,totalBytes>maxBytes)throw await reader.cancel(),new Error(`OpenAPI spec from ${url} exceeds the ${maxBytes} byte limit.`);chunks.push(value)}}let buffer=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)buffer.set(chunk,offset),offset+=chunk.byteLength;return JSON.parse(new TextDecoder().decode(buffer))}var ALLOWED_SPEC_HOSTS=["vercel.sh","vercel.tools"];function assertAllowedSpecUrl(specUrl){let parsedUrl=new URL(specUrl);if(parsedUrl.protocol!=="https:")throw new Error("OpenAPI spec URL must use https");if(!ALLOWED_SPEC_HOSTS.some(host=>isHostOrSubdomain(parsedUrl,host)))throw new Error("OpenAPI spec URL must be on an allowed origin.");return parsedUrl}function isHostOrSubdomain(url,host){return url.hostname===host||url.hostname.endsWith(`.${host}`)}import{join}from"path";import{readFile,writeFile,mkdir}from"fs/promises";var OpenApiCache=class{constructor(options){this.spec=null;this.error=null;this.cachePath=join(getGlobalPathConfig(),CACHE_FILE),this.specUrl=options?.specUrl,this.fetchSpecUrl=options?.fetchSpecUrl}get isLoaded(){return this.spec!==null}get loadError(){return this.error}async load(forceRefresh=!1){return this.loadSpec(forceRefresh)}async loadSpec(forceRefresh=!1){if(this.error=null,this.specUrl)return this.loadCustomSpec(this.specUrl);if(!forceRefresh){let cached=await this.readCache(this.cachePath);if(cached&&!this.isExpired(cached.fetchedAt))return output_manager_default.debug("Using cached OpenAPI spec"),this.spec=cached.spec,!0}try{return output_manager_default.debug("Fetching OpenAPI spec from "+OPENAPI_URL),this.spec=await this.fetchSpec(OPENAPI_URL),await this.saveCache(this.cachePath,this.spec),!0}catch(err){output_manager_default.debug(`Failed to fetch OpenAPI spec: ${err}`);let stale=await this.readCache(this.cachePath);return stale?(output_manager_default.debug("Using stale cached OpenAPI spec"),this.spec=stale.spec,!0):!1}}async loadCustomSpec(specUrl){try{assertAllowedSpecUrl(specUrl),output_manager_default.debug("Fetching OpenAPI spec from "+specUrl);let spec=this.fetchSpecUrl?await this.fetchSpecUrl(specUrl):await this.fetchSpec(specUrl);return spec?(this.validateSpec(spec,specUrl),this.spec=spec,!!this.spec):(this.error=`Could not load OpenAPI spec from ${specUrl}.`,!1)}catch(err){let message=err instanceof Error?err.message:String(err);return this.error=message,output_manager_default.debug(`Failed to fetch OpenAPI spec from ${specUrl}: ${message}`),!1}}async loadWithSpinner(forceRefresh=!1){output_manager_default.spinner(forceRefresh?"Refreshing API endpoints...":"Loading API endpoints...");let success=await this.load(forceRefresh);return output_manager_default.stopSpinner(),success}getEndpoints(){this.ensureLoaded();let endpoints=this.extractEndpoints();return this.sortEndpoints(endpoints)}getBodyFields(endpoint){if(this.ensureLoaded(),!endpoint.requestBody?.content)return[];let jsonContent=endpoint.requestBody.content["application/json"];if(!jsonContent?.schema)return[];let schema=this.resolveSchemaRef(jsonContent.schema);if(!schema?.properties)return[];let requiredFields=new Set(schema.required||[]),fields=[];for(let[name,propSchema]of Object.entries(schema.properties)){let resolvedProp=this.resolveSchemaRef(propSchema),enumValues=resolvedProp?.enum||propSchema.enum;if(!enumValues&&(resolvedProp?.type==="array"||propSchema.type==="array")){let items=resolvedProp?.items||propSchema.items;items&&(enumValues=this.resolveSchemaRef(items)?.enum||items.enum)}fields.push({name,required:requiredFields.has(name),description:resolvedProp?.description||propSchema.description,type:resolvedProp?.type||propSchema.type,enumValues})}return fields.sort((a,b)=>a.required!==b.required?a.required?-1:1:a.name.localeCompare(b.name)),fields}getDisplayColumns(endpoint){this.ensureLoaded();let pathItem=this.spec.paths[endpoint.path];if(!pathItem)return null;let operation=pathItem[endpoint.method.toLowerCase()];if(!operation?.responses)return null;let ok=operation.responses[200]||operation.responses[201];if(!ok)return null;let jsonContent=ok.content?.["application/json"];return jsonContent?.schema?this.findDisplayColumns(jsonContent.schema):null}findDisplayColumns(schema){let xCli=schema["x-vercel-cli"];if(xCli?.displayColumns)return xCli.displayColumns;for(let key of["oneOf","allOf","anyOf"]){let variants=schema[key];if(variants)for(let sub of variants){let found=this.findDisplayColumns(sub);if(found)return found}}return null}ensureLoaded(){if(!this.spec)throw new Error("OpenAPI spec not loaded. Call load() or loadWithSpinner() first.")}async readCache(cachePath){try{let content=await readFile(cachePath,"utf-8");return JSON.parse(content)}catch{return null}}async saveCache(cachePath,spec){let cached={fetchedAt:Date.now(),spec},dir=join(cachePath,"..");await mkdir(dir,{recursive:!0}),await writeFile(cachePath,JSON.stringify(cached)),output_manager_default.debug("Saved OpenAPI spec to cache")}async fetchSpec(url){let controller=new AbortController,timeoutId=setTimeout(()=>controller.abort(),1e4);try{let response=await fetch(url,{signal:controller.signal});if(!response.ok)throw new Error(`Failed to fetch OpenAPI spec: ${response.status}`);let spec=await readSpecResponse(response,url);return this.validateSpec(spec,url),spec}finally{clearTimeout(timeoutId)}}validateSpec(spec,url){if(!spec||typeof spec!="object")throw new Error(`Invalid OpenAPI spec from ${url}: expected a JSON object.`);if(typeof spec.openapi!="string"||!spec.openapi.startsWith("3."))throw new Error(`Invalid OpenAPI spec from ${url}: expected an OpenAPI 3.x document with an "openapi" field.`);if(!spec.paths||typeof spec.paths!="object")throw new Error(`Invalid OpenAPI spec from ${url}: expected a "paths" object.`);for(let path of Object.keys(spec.paths))if(!path.startsWith("/")||path.startsWith("//"))throw new Error(`Invalid OpenAPI spec from ${url}: path "${path}" must be a relative API path.`)}isExpired(fetchedAt){return Date.now()-fetchedAt>864e5}sortEndpoints(endpoints){return endpoints.sort((a,b)=>{let pathCompare=a.path.localeCompare(b.path);return pathCompare!==0?pathCompare:a.method.localeCompare(b.method)})}extractEndpoints(){let endpoints=[];for(let[path,pathItem]of Object.entries(this.spec.paths)){let methods=["get","post","put","patch","delete"];for(let method of methods){let operation=pathItem[method];if(operation){let pathParams=pathItem.parameters||[],opParams=operation.parameters||[],allParams=[...pathParams,...opParams];endpoints.push({path,method:method.toUpperCase(),summary:operation.summary||pathItem.summary||"",description:operation.description||pathItem.description||"",operationId:operation.operationId||"",tags:operation.tags||[],parameters:allParams,requestBody:operation.requestBody})}}}return endpoints}resolveSchemaRef(schema,spec=this.spec){if(schema){if(schema.$ref){let match=schema.$ref.match(/^#\/components\/schemas\/(.+)$/);if(match&&spec.components?.schemas){let resolved=spec.components.schemas[match[1]];return this.resolveSchemaRef(resolved,spec)}return}if(schema.allOf&&schema.allOf.length>0){let merged={type:"object",properties:{},required:[]};for(let subSchema of schema.allOf){let resolved=this.resolveSchemaRef(subSchema,spec);resolved&&(resolved.properties&&(merged.properties={...merged.properties,...resolved.properties}),resolved.required&&(merged.required=[...merged.required||[],...resolved.required]))}return merged}return schema}}};async function matchesCliApiTag(tagHint){if(!tagHint||tagHint.startsWith("-")||tagHint.includes("/"))return!1;let cache=new OpenApiCache;if(!await cache.load())return!1;let endpoints=cache.getEndpoints(),lower=tagHint.toLowerCase();return endpoints.some(ep=>ep.tags.some(t=>t.toLowerCase()===lower))}async function resolveOpenApiTagForProjectsCli(){return await matchesCliApiTag("projects")?"projects":await matchesCliApiTag("project")?"project":null}async function resolveOpenApiTagForTeamsCli(){return await matchesCliApiTag("teams")?"teams":await matchesCliApiTag("team")?"team":null}export{OPENAPI_URL,SSO_API_URL,CACHE_FILE,CACHE_TTL_MS,FETCH_TIMEOUT_MS,MAX_OPENAPI_SPEC_BYTES,VERCEL_CLI_ROOT_DISPLAY_KEY,readSpecResponse,assertAllowedSpecUrl,OpenApiCache,matchesCliApiTag,resolveOpenApiTagForProjectsCli,resolveOpenApiTagForTeamsCli};
7
+ import{getGlobalPathConfig}from"./chunk-GTZDB7IL.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";var OPENAPI_URL="https://openapi.vercel.sh/",SSO_API_URL="https://vercel.com/sso-api",CACHE_FILE="openapi-spec.json",CACHE_TTL_MS=864e5,FETCH_TIMEOUT_MS=1e4,MAX_OPENAPI_SPEC_BYTES=52428800,VERCEL_CLI_ROOT_DISPLAY_KEY="__root__";async function readSpecResponse(response,url,maxBytes=52428800){let contentLength=response.headers.get("content-length");if(contentLength){let bytes=Number(contentLength);if(Number.isFinite(bytes)&&bytes>maxBytes)throw new Error(`OpenAPI spec from ${url} exceeds the ${maxBytes} byte limit.`)}if(!response.body)throw new Error(`OpenAPI spec from ${url} returned an empty response.`);let reader=response.body.getReader(),chunks=[],totalBytes=0;for(;;){let{done,value}=await reader.read();if(done)break;if(value){if(totalBytes+=value.byteLength,totalBytes>maxBytes)throw await reader.cancel(),new Error(`OpenAPI spec from ${url} exceeds the ${maxBytes} byte limit.`);chunks.push(value)}}let buffer=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)buffer.set(chunk,offset),offset+=chunk.byteLength;return JSON.parse(new TextDecoder().decode(buffer))}var ALLOWED_SPEC_HOSTS=["vercel.sh","vercel.tools"];function assertAllowedSpecUrl(specUrl){let parsedUrl=new URL(specUrl);if(parsedUrl.protocol!=="https:")throw new Error("OpenAPI spec URL must use https");if(!ALLOWED_SPEC_HOSTS.some(host=>isHostOrSubdomain(parsedUrl,host)))throw new Error("OpenAPI spec URL must be on an allowed origin.");return parsedUrl}function isHostOrSubdomain(url,host){return url.hostname===host||url.hostname.endsWith(`.${host}`)}import{join}from"path";import{readFile,writeFile,mkdir}from"fs/promises";var OpenApiCache=class{constructor(options){this.spec=null;this.error=null;this.cachePath=join(getGlobalPathConfig(),CACHE_FILE),this.specUrl=options?.specUrl,this.fetchSpecUrl=options?.fetchSpecUrl}get isLoaded(){return this.spec!==null}get loadError(){return this.error}async load(forceRefresh=!1){return this.loadSpec(forceRefresh)}async loadSpec(forceRefresh=!1){if(this.error=null,this.specUrl)return this.loadCustomSpec(this.specUrl);if(!forceRefresh){let cached=await this.readCache(this.cachePath);if(cached&&!this.isExpired(cached.fetchedAt))return output_manager_default.debug("Using cached OpenAPI spec"),this.spec=cached.spec,!0}try{return output_manager_default.debug("Fetching OpenAPI spec from "+OPENAPI_URL),this.spec=await this.fetchSpec(OPENAPI_URL),await this.saveCache(this.cachePath,this.spec),!0}catch(err){output_manager_default.debug(`Failed to fetch OpenAPI spec: ${err}`);let stale=await this.readCache(this.cachePath);return stale?(output_manager_default.debug("Using stale cached OpenAPI spec"),this.spec=stale.spec,!0):!1}}async loadCustomSpec(specUrl){try{assertAllowedSpecUrl(specUrl),output_manager_default.debug("Fetching OpenAPI spec from "+specUrl);let spec=this.fetchSpecUrl?await this.fetchSpecUrl(specUrl):await this.fetchSpec(specUrl);return spec?(this.validateSpec(spec,specUrl),this.spec=spec,!!this.spec):(this.error=`Could not load OpenAPI spec from ${specUrl}.`,!1)}catch(err){let message=err instanceof Error?err.message:String(err);return this.error=message,output_manager_default.debug(`Failed to fetch OpenAPI spec from ${specUrl}: ${message}`),!1}}async loadWithSpinner(forceRefresh=!1){output_manager_default.spinner(forceRefresh?"Refreshing API endpoints...":"Loading API endpoints...");let success=await this.load(forceRefresh);return output_manager_default.stopSpinner(),success}getEndpoints(){this.ensureLoaded();let endpoints=this.extractEndpoints();return this.sortEndpoints(endpoints)}getBodyFields(endpoint){if(this.ensureLoaded(),!endpoint.requestBody?.content)return[];let jsonContent=endpoint.requestBody.content["application/json"];if(!jsonContent?.schema)return[];let schema=this.resolveSchemaRef(jsonContent.schema);if(!schema?.properties)return[];let requiredFields=new Set(schema.required||[]),fields=[];for(let[name,propSchema]of Object.entries(schema.properties)){let resolvedProp=this.resolveSchemaRef(propSchema),enumValues=resolvedProp?.enum||propSchema.enum;if(!enumValues&&(resolvedProp?.type==="array"||propSchema.type==="array")){let items=resolvedProp?.items||propSchema.items;items&&(enumValues=this.resolveSchemaRef(items)?.enum||items.enum)}fields.push({name,required:requiredFields.has(name),description:resolvedProp?.description||propSchema.description,type:resolvedProp?.type||propSchema.type,enumValues})}return fields.sort((a,b)=>a.required!==b.required?a.required?-1:1:a.name.localeCompare(b.name)),fields}getDisplayColumns(endpoint){this.ensureLoaded();let pathItem=this.spec.paths[endpoint.path];if(!pathItem)return null;let operation=pathItem[endpoint.method.toLowerCase()];if(!operation?.responses)return null;let ok=operation.responses[200]||operation.responses[201];if(!ok)return null;let jsonContent=ok.content?.["application/json"];return jsonContent?.schema?this.findDisplayColumns(jsonContent.schema):null}findDisplayColumns(schema){let xCli=schema["x-vercel-cli"];if(xCli?.displayColumns)return xCli.displayColumns;for(let key of["oneOf","allOf","anyOf"]){let variants=schema[key];if(variants)for(let sub of variants){let found=this.findDisplayColumns(sub);if(found)return found}}return null}ensureLoaded(){if(!this.spec)throw new Error("OpenAPI spec not loaded. Call load() or loadWithSpinner() first.")}async readCache(cachePath){try{let content=await readFile(cachePath,"utf-8");return JSON.parse(content)}catch{return null}}async saveCache(cachePath,spec){let cached={fetchedAt:Date.now(),spec},dir=join(cachePath,"..");await mkdir(dir,{recursive:!0}),await writeFile(cachePath,JSON.stringify(cached)),output_manager_default.debug("Saved OpenAPI spec to cache")}async fetchSpec(url){let controller=new AbortController,timeoutId=setTimeout(()=>controller.abort(),1e4);try{let response=await fetch(url,{signal:controller.signal});if(!response.ok)throw new Error(`Failed to fetch OpenAPI spec: ${response.status}`);let spec=await readSpecResponse(response,url);return this.validateSpec(spec,url),spec}finally{clearTimeout(timeoutId)}}validateSpec(spec,url){if(!spec||typeof spec!="object")throw new Error(`Invalid OpenAPI spec from ${url}: expected a JSON object.`);if(typeof spec.openapi!="string"||!spec.openapi.startsWith("3."))throw new Error(`Invalid OpenAPI spec from ${url}: expected an OpenAPI 3.x document with an "openapi" field.`);if(!spec.paths||typeof spec.paths!="object")throw new Error(`Invalid OpenAPI spec from ${url}: expected a "paths" object.`);for(let path of Object.keys(spec.paths))if(!path.startsWith("/")||path.startsWith("//"))throw new Error(`Invalid OpenAPI spec from ${url}: path "${path}" must be a relative API path.`)}isExpired(fetchedAt){return Date.now()-fetchedAt>864e5}sortEndpoints(endpoints){return endpoints.sort((a,b)=>{let pathCompare=a.path.localeCompare(b.path);return pathCompare!==0?pathCompare:a.method.localeCompare(b.method)})}extractEndpoints(){let endpoints=[];for(let[path,pathItem]of Object.entries(this.spec.paths)){let methods=["get","post","put","patch","delete"];for(let method of methods){let operation=pathItem[method];if(operation){let pathParams=pathItem.parameters||[],opParams=operation.parameters||[],allParams=[...pathParams,...opParams];endpoints.push({path,method:method.toUpperCase(),summary:operation.summary||pathItem.summary||"",description:operation.description||pathItem.description||"",operationId:operation.operationId||"",tags:operation.tags||[],parameters:allParams,requestBody:operation.requestBody})}}}return endpoints}resolveSchemaRef(schema,spec=this.spec){if(schema){if(schema.$ref){let match=schema.$ref.match(/^#\/components\/schemas\/(.+)$/);if(match&&spec.components?.schemas){let resolved=spec.components.schemas[match[1]];return this.resolveSchemaRef(resolved,spec)}return}if(schema.allOf&&schema.allOf.length>0){let merged={type:"object",properties:{},required:[]};for(let subSchema of schema.allOf){let resolved=this.resolveSchemaRef(subSchema,spec);resolved&&(resolved.properties&&(merged.properties={...merged.properties,...resolved.properties}),resolved.required&&(merged.required=[...merged.required||[],...resolved.required]))}return merged}return schema}}};async function matchesCliApiTag(tagHint){if(!tagHint||tagHint.startsWith("-")||tagHint.includes("/"))return!1;let cache=new OpenApiCache;if(!await cache.load())return!1;let endpoints=cache.getEndpoints(),lower=tagHint.toLowerCase();return endpoints.some(ep=>ep.tags.some(t=>t.toLowerCase()===lower))}async function resolveOpenApiTagForProjectsCli(){return await matchesCliApiTag("projects")?"projects":await matchesCliApiTag("project")?"project":null}async function resolveOpenApiTagForTeamsCli(){return await matchesCliApiTag("teams")?"teams":await matchesCliApiTag("team")?"team":null}export{OPENAPI_URL,SSO_API_URL,CACHE_FILE,CACHE_TTL_MS,FETCH_TIMEOUT_MS,MAX_OPENAPI_SPEC_BYTES,VERCEL_CLI_ROOT_DISPLAY_KEY,readSpecResponse,assertAllowedSpecUrl,OpenApiCache,matchesCliApiTag,resolveOpenApiTagForProjectsCli,resolveOpenApiTagForTeamsCli};
@@ -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{tracesConfigCommand}from"./chunk-3R66O72V.js";import{deploymentOption,projectOption,protectionBypassOption,yesOption}from"./chunk-PV5YI2ZZ.js";import{packageName}from"./chunk-FI772UVH.js";var spanQueryOptions=[{...projectOption,shorthand:"p",description:"Filter spans to one project (default: all team projects)"},{name:"environment",shorthand:null,type:String,deprecated:!1,description:"Environment: production or preview (case-insensitive)"},{name:"service",shorthand:null,type:String,deprecated:!1,description:"Filter by service name"},{name:"name",shorthand:null,type:String,deprecated:!1,description:"Filter by span name"},{name:"kind",shorthand:null,type:String,deprecated:!1,description:"Filter by span kind: unspecified (0), internal (1), server (2), client (3), producer (4), consumer (5)"},{name:"status",shorthand:null,type:String,deprecated:!1,description:"Status: error, ok, or unset (case-insensitive)"},{name:"deployment-id",shorthand:null,type:String,deprecated:!1,description:"Filter by deployment ID"},{name:"request-id",shorthand:null,type:String,deprecated:!1,description:"Filter by request ID. Some IDs return 404 in traces get. Reuse --scope and --project. See traces get --help."},{name:"trace-id",shorthand:null,type:String,deprecated:!1,description:"Filter by trace ID"},{name:"span-id",shorthand:null,type:String,deprecated:!1,description:"Filter by span ID"},{name:"root",shorthand:null,type:Boolean,deprecated:!1,description:"Show root spans only"},{name:"since",shorthand:null,type:String,deprecated:!1,description:"Start time: 30m, ISO timestamp, or YYYY-MM-DD UTC (default: 1h)"},{name:"until",shorthand:null,type:String,deprecated:!1,description:"End time: same formats as --since (default: now)"}];var requestIdLookupHelp={title:"Request-ID lookup",body:["A request ID in search results does not guarantee traces get can retrieve the trace. Lookup requires a matching root span in the same project within 30 minutes after the request-ID timestamp.","","If no matching root is found, lookup returns 404. Use the same --scope and --project for search and get."]},getSubcommand={name:"get",aliases:[],default:!0,description:"Fetch a captured trace by trace ID or request ID",helpSections:[{title:"Trace-ID lookup",body:["A 32-character hexadecimal ID selects trace-ID lookup. Other IDs select request-ID lookup.","Trace-ID lookup retrieves the trace directly within the trace retention window. Use the same --scope and --project as search."]},requestIdLookupHelp],arguments:[{name:"id",required:!0}],options:[{name:"json",shorthand:null,type:Boolean,deprecated:!1,description:"Print the raw trace JSON to stdout"},{name:"project",shorthand:null,type:String,argument:"NAME|ID",deprecated:!1,description:"Project name or id to fetch the trace from (overrides the linked project)."},{name:"open",shorthand:null,type:Boolean,deprecated:!1,description:"Open the trace in the Vercel Dashboard instead of printing it."},{name:"view",shorthand:null,type:String,argument:"timeline|tree|waterfall",deprecated:!1,description:"Dashboard view to open. Only valid with --open. Defaults to timeline."}],examples:[{name:"Fetch a trace by trace ID",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00`},{name:"Fetch a trace by request ID",value:`${packageName} traces get qb46r-1790847620933-1145d2891a3e`},{name:"Print the raw trace JSON",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00 --json`},{name:"Fetch a trace without the default get subcommand",value:`${packageName} traces e5c0d1efb3904155472b01692c7f2d00`},{name:"Fetch a trace from a specific team and project",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00 --scope my-team --project my-app`},{name:"Open the trace in the Vercel Dashboard",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00 --open`},{name:"Open the trace in the Vercel Dashboard with the waterfall view",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00 --open --view waterfall`}]},createSubcommand={name:"create",aliases:[],description:"Capture a session trace for a request (alias for `vercel curl --trace`).",arguments:[{name:"path",required:!0}],options:[deploymentOption,protectionBypassOption,{name:"json",shorthand:null,type:Boolean,deprecated:!1,description:"Emit { response, requestId } as JSON on stdout"},{...yesOption,description:"Skip the production confirmation prompt (e.g. in non-interactive mode)"}],examples:[{name:"Capture a session trace for a request",value:`${packageName} traces create /api/hello`},{name:"Target a specific deployment",value:`${packageName} traces create /api/status --deployment https://your-project-abc123.vercel.app`},{name:"Pass curl flags after the separator",value:`${packageName} traces create /api/test -- --request POST --data '{"name": "John"}'`}]},searchSubcommand={name:"search",aliases:[],description:"Search team spans. Use --project to filter one project. Results are newest first. Duration filters do not sort results.",helpSections:[{title:"Table columns",body:["Available: span.startTime, span.duration, span.name, span.status.code, service.name, environment, request.id, trace.id, span.id, parent.id, span.kind","Default: all except environment, request.id, and span.kind."]},{title:"KQL filters",body:["Fields: project.id, environment, service.name, deployment.id, request.id, user.id, session.id","Span fields: span.name, span.kind, span.id, parent.id, span.isRoot, span.status.code, span.duration","Trace fields: trace.id, trace.state","","Other fields search span attributes first, then resource attributes.","","span.duration uses milliseconds.","span.kind uses the numeric values shown under --kind.","span.status.code uses Error, Ok, or Unset.","Use field:value filters. Plain text search is not supported.","Use NOT to exclude values. End a value with * to match a prefix.","Wrap values with spaces in double quotes. Keep the full query in single quotes."]}],arguments:[],options:[...spanQueryOptions,{name:"limit",shorthand:"n",type:Number,deprecated:!1,description:"Maximum number of spans (default: 100)"},{name:"query",shorthand:"q",type:String,deprecated:!1,description:"Filter spans using KQL"},{name:"columns",shorthand:null,argument:"LIST",type:String,deprecated:!1,description:"Columns to show, in order. Separate names with commas. Cannot be used with --json or --non-interactive."},{name:"json",shorthand:"j",type:Boolean,deprecated:!1,description:"Output one JSON object per line"}],examples:[{name:"Find production errors for one service",value:`${packageName} traces search --environment production --service checkout-api --status error --since 1h`},{name:"Use KQL and output JSON Lines",value:`${packageName} traces search --query 'http.route:"/api/checkout"' --kind server --json`},{name:"Exclude span names starting with app/lib/fetch-api",value:`${packageName} traces search --query 'NOT span.name:app/lib/fetch-api*'`},{name:"Exclude exact span names",value:`${packageName} traces search --query 'NOT span.name:("GET /screenshot/v2" OR "middleware GET")'`},{name:"Find spans longer than 2 seconds",value:`${packageName} traces search --query 'span.duration > 2000' --columns span.startTime,span.duration,span.name,span.kind,span.status.code`}]},tracesCommand={name:"traces",aliases:[],description:"Fetch project traces and search spans across a Vercel team.",arguments:[{name:"id",required:!1}],subcommands:[getSubcommand,searchSubcommand,createSubcommand,tracesConfigCommand],options:[],examples:[{name:"Fetch a trace by trace ID",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00`},{name:"Fetch a trace by request ID",value:`${packageName} traces get qb46r-1790847620933-1145d2891a3e`},{name:"Print the raw trace JSON",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00 --json`},{name:"Capture a session trace for a request",value:`${packageName} traces create /api/hello`},{name:"Search recent spans",value:`${packageName} traces search --status error`},{name:"List the trace sampling rules for a project",value:`${packageName} traces config ls`}]};export{getSubcommand,createSubcommand,searchSubcommand,tracesCommand};
7
+ import{tracesConfigCommand}from"./chunk-AUIBCIET.js";import{deploymentOption,projectOption,protectionBypassOption,yesOption}from"./chunk-ROOWZCAB.js";import{packageName}from"./chunk-FI772UVH.js";var spanQueryOptions=[{...projectOption,shorthand:"p",description:"Filter spans to one project (default: all team projects)"},{name:"environment",shorthand:null,type:String,deprecated:!1,description:"Environment: production or preview (case-insensitive)"},{name:"service",shorthand:null,type:String,deprecated:!1,description:"Filter by service name"},{name:"name",shorthand:null,type:String,deprecated:!1,description:"Filter by span name"},{name:"kind",shorthand:null,type:String,deprecated:!1,description:"Filter by span kind: unspecified (0), internal (1), server (2), client (3), producer (4), consumer (5)"},{name:"status",shorthand:null,type:String,deprecated:!1,description:"Status: error, ok, or unset (case-insensitive)"},{name:"deployment-id",shorthand:null,type:String,deprecated:!1,description:"Filter by deployment ID"},{name:"request-id",shorthand:null,type:String,deprecated:!1,description:"Filter by request ID. Some IDs return 404 in traces get. Reuse --scope and --project. See traces get --help."},{name:"trace-id",shorthand:null,type:String,deprecated:!1,description:"Filter by trace ID"},{name:"span-id",shorthand:null,type:String,deprecated:!1,description:"Filter by span ID"},{name:"root",shorthand:null,type:Boolean,deprecated:!1,description:"Show root spans only"},{name:"since",shorthand:null,type:String,deprecated:!1,description:"Start time: 30m, ISO timestamp, or YYYY-MM-DD UTC (default: 1h)"},{name:"until",shorthand:null,type:String,deprecated:!1,description:"End time: same formats as --since (default: now)"}];var requestIdLookupHelp={title:"Request-ID lookup",body:["A request ID in search results does not guarantee traces get can retrieve the trace. Lookup requires a matching root span in the same project within 30 minutes after the request-ID timestamp.","","If no matching root is found, lookup returns 404. Use the same --scope and --project for search and get."]},getSubcommand={name:"get",aliases:[],default:!0,description:"Fetch a captured trace by trace ID or request ID",helpSections:[{title:"Trace-ID lookup",body:["A 32-character hexadecimal ID selects trace-ID lookup. Other IDs select request-ID lookup.","Trace-ID lookup retrieves the trace directly within the trace retention window. Use the same --scope and --project as search."]},requestIdLookupHelp],arguments:[{name:"id",required:!0}],options:[{name:"json",shorthand:null,type:Boolean,deprecated:!1,description:"Print the raw trace JSON to stdout"},{name:"project",shorthand:null,type:String,argument:"NAME|ID",deprecated:!1,description:"Project name or id to fetch the trace from (overrides the linked project)."},{name:"open",shorthand:null,type:Boolean,deprecated:!1,description:"Open the trace in the Vercel Dashboard instead of printing it."},{name:"view",shorthand:null,type:String,argument:"timeline|tree|waterfall",deprecated:!1,description:"Dashboard view to open. Only valid with --open. Defaults to timeline."}],examples:[{name:"Fetch a trace by trace ID",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00`},{name:"Fetch a trace by request ID",value:`${packageName} traces get qb46r-1790847620933-1145d2891a3e`},{name:"Print the raw trace JSON",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00 --json`},{name:"Fetch a trace without the default get subcommand",value:`${packageName} traces e5c0d1efb3904155472b01692c7f2d00`},{name:"Fetch a trace from a specific team and project",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00 --scope my-team --project my-app`},{name:"Open the trace in the Vercel Dashboard",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00 --open`},{name:"Open the trace in the Vercel Dashboard with the waterfall view",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00 --open --view waterfall`}]},createSubcommand={name:"create",aliases:[],description:"Capture a session trace for a request (alias for `vercel curl --trace`).",arguments:[{name:"path",required:!0}],options:[deploymentOption,protectionBypassOption,{name:"json",shorthand:null,type:Boolean,deprecated:!1,description:"Emit { response, requestId } as JSON on stdout"},{...yesOption,description:"Skip the production confirmation prompt (e.g. in non-interactive mode)"}],examples:[{name:"Capture a session trace for a request",value:`${packageName} traces create /api/hello`},{name:"Target a specific deployment",value:`${packageName} traces create /api/status --deployment https://your-project-abc123.vercel.app`},{name:"Pass curl flags after the separator",value:`${packageName} traces create /api/test -- --request POST --data '{"name": "John"}'`}]},searchSubcommand={name:"search",aliases:[],description:"Search team spans. Use --project to filter one project. Results are newest first. Duration filters do not sort results.",helpSections:[{title:"Table columns",body:["Available: span.startTime, span.duration, span.name, span.status.code, service.name, environment, request.id, trace.id, span.id, parent.id, span.kind","Default: all except environment, request.id, and span.kind."]},{title:"KQL filters",body:["Fields: project.id, environment, service.name, deployment.id, request.id, user.id, session.id","Span fields: span.name, span.kind, span.id, parent.id, span.isRoot, span.status.code, span.duration","Trace fields: trace.id, trace.state","","Other fields search span attributes first, then resource attributes.","","span.duration uses milliseconds.","span.kind uses the numeric values shown under --kind.","span.status.code uses Error, Ok, or Unset.","Use field:value filters. Plain text search is not supported.","Use NOT to exclude values. End a value with * to match a prefix.","Wrap values with spaces in double quotes. Keep the full query in single quotes."]}],arguments:[],options:[...spanQueryOptions,{name:"limit",shorthand:"n",type:Number,deprecated:!1,description:"Maximum number of spans (default: 100)"},{name:"query",shorthand:"q",type:String,deprecated:!1,description:"Filter spans using KQL"},{name:"columns",shorthand:null,argument:"LIST",type:String,deprecated:!1,description:"Columns to show, in order. Separate names with commas. Cannot be used with --json or --non-interactive."},{name:"json",shorthand:"j",type:Boolean,deprecated:!1,description:"Output one JSON object per line"}],examples:[{name:"Find production errors for one service",value:`${packageName} traces search --environment production --service checkout-api --status error --since 1h`},{name:"Use KQL and output JSON Lines",value:`${packageName} traces search --query 'http.route:"/api/checkout"' --kind server --json`},{name:"Exclude span names starting with app/lib/fetch-api",value:`${packageName} traces search --query 'NOT span.name:app/lib/fetch-api*'`},{name:"Exclude exact span names",value:`${packageName} traces search --query 'NOT span.name:("GET /screenshot/v2" OR "middleware GET")'`},{name:"Find spans longer than 2 seconds",value:`${packageName} traces search --query 'span.duration > 2000' --columns span.startTime,span.duration,span.name,span.kind,span.status.code`}]},tracesCommand={name:"traces",aliases:[],description:"Fetch project traces and search spans across a Vercel team.",arguments:[{name:"id",required:!1}],subcommands:[getSubcommand,searchSubcommand,createSubcommand,tracesConfigCommand],options:[],examples:[{name:"Fetch a trace by trace ID",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00`},{name:"Fetch a trace by request ID",value:`${packageName} traces get qb46r-1790847620933-1145d2891a3e`},{name:"Print the raw trace JSON",value:`${packageName} traces get e5c0d1efb3904155472b01692c7f2d00 --json`},{name:"Capture a session trace for a request",value:`${packageName} traces create /api/hello`},{name:"Search recent spans",value:`${packageName} traces search --status error`},{name:"List the trace sampling rules for a project",value:`${packageName} traces config ls`}]};export{getSubcommand,createSubcommand,searchSubcommand,tracesCommand};
@@ -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{__commonJS,__require}from"./chunk-6L236MNA.js";var require_deque=__commonJS({"../../node_modules/.pnpm/double-ended-queue@2.1.0-0/node_modules/double-ended-queue/js/deque.js"(exports,module){"use strict";function Deque(capacity){if(this._capacity=getCapacity(capacity),this._length=0,this._front=0,isArray(capacity)){for(var len=capacity.length,i=0;i<len;++i)this[i]=capacity[i];this._length=len}}Deque.prototype.toArray=function(){for(var len=this._length,ret=new Array(len),front=this._front,capacity=this._capacity,j=0;j<len;++j)ret[j]=this[front+j&capacity-1];return ret};Deque.prototype.push=function(item){var argsLength=arguments.length,length=this._length;if(argsLength>1){var capacity=this._capacity;if(length+argsLength>capacity){for(var i=0;i<argsLength;++i){this._checkCapacity(length+1);var j=this._front+length&this._capacity-1;this[j]=arguments[i],length++,this._length=length}return length}else{for(var j=this._front,i=0;i<argsLength;++i)this[j+length&capacity-1]=arguments[i],j++;return this._length=length+argsLength,length+argsLength}}if(argsLength===0)return length;this._checkCapacity(length+1);var i=this._front+length&this._capacity-1;return this[i]=item,this._length=length+1,length+1};Deque.prototype.pop=function(){var length=this._length;if(length!==0){var i=this._front+length-1&this._capacity-1,ret=this[i];return this[i]=void 0,this._length=length-1,ret}};Deque.prototype.shift=function(){var length=this._length;if(length!==0){var front=this._front,ret=this[front];return this[front]=void 0,this._front=front+1&this._capacity-1,this._length=length-1,ret}};Deque.prototype.unshift=function(item){var length=this._length,argsLength=arguments.length;if(argsLength>1){var capacity=this._capacity;if(length+argsLength>capacity){for(var i=argsLength-1;i>=0;i--){this._checkCapacity(length+1);var capacity=this._capacity,j=(this._front-1&capacity-1^capacity)-capacity;this[j]=arguments[i],length++,this._length=length,this._front=j}return length}else{for(var front=this._front,i=argsLength-1;i>=0;i--){var j=(front-1&capacity-1^capacity)-capacity;this[j]=arguments[i],front=j}return this._front=front,this._length=length+argsLength,length+argsLength}}if(argsLength===0)return length;this._checkCapacity(length+1);var capacity=this._capacity,i=(this._front-1&capacity-1^capacity)-capacity;return this[i]=item,this._length=length+1,this._front=i,length+1};Deque.prototype.peekBack=function(){var length=this._length;if(length!==0){var index=this._front+length-1&this._capacity-1;return this[index]}};Deque.prototype.peekFront=function(){if(this._length!==0)return this[this._front]};Deque.prototype.get=function(index){var i=index;if(i===(i|0)){var len=this._length;if(i<0&&(i=i+len),!(i<0||i>=len))return this[this._front+i&this._capacity-1]}};Deque.prototype.isEmpty=function(){return this._length===0};Deque.prototype.clear=function(){for(var len=this._length,front=this._front,capacity=this._capacity,j=0;j<len;++j)this[front+j&capacity-1]=void 0;this._length=0,this._front=0};Deque.prototype.toString=function(){return this.toArray().toString()};Deque.prototype.valueOf=Deque.prototype.toString;Deque.prototype.removeFront=Deque.prototype.shift;Deque.prototype.removeBack=Deque.prototype.pop;Deque.prototype.insertFront=Deque.prototype.unshift;Deque.prototype.insertBack=Deque.prototype.push;Deque.prototype.enqueue=Deque.prototype.push;Deque.prototype.dequeue=Deque.prototype.shift;Deque.prototype.toJSON=Deque.prototype.toArray;Object.defineProperty(Deque.prototype,"length",{get:function(){return this._length},set:function(){throw new RangeError("")}});Deque.prototype._checkCapacity=function(size){this._capacity<size&&this._resizeTo(getCapacity(this._capacity*1.5+16))};Deque.prototype._resizeTo=function(capacity){var oldCapacity=this._capacity;this._capacity=capacity;var front=this._front,length=this._length;if(front+length>oldCapacity){var moveItemsCount=front+length&oldCapacity-1;arrayMove(this,0,this,oldCapacity,moveItemsCount)}};var isArray=Array.isArray;function arrayMove(src,srcIndex,dst,dstIndex,len){for(var j=0;j<len;++j)dst[j+dstIndex]=src[j+srcIndex],src[j+srcIndex]=void 0}function pow2AtLeast(n){return n=n>>>0,n=n-1,n=n|n>>1,n=n|n>>2,n=n|n>>4,n=n|n>>8,n=n|n>>16,n+1}function getCapacity(capacity){if(typeof capacity!="number")if(isArray(capacity))capacity=capacity.length;else return 16;return pow2AtLeast(Math.min(Math.max(16,capacity),1073741824))}module.exports=Deque}});var require_async_sema=__commonJS({"../../node_modules/.pnpm/async-sema@2.1.4/node_modules/async-sema/index.js"(exports,module){var EventEmitter=__require("events"),util=__require("util"),Deque=require_deque(),ReleaseEmitter=class extends EventEmitter{};function isFn(x){return typeof x=="function"}function defaultInit(){return"1"}var Sema=class{constructor(nr,{initFn=defaultInit,pauseFn,resumeFn,capacity=10}={}){if(isFn(pauseFn)^isFn(resumeFn))throw new Error("pauseFn and resumeFn must be both set for pausing");this.nrTokens=nr,this.free=new Deque(nr),this.waiting=new Deque(capacity),this.releaseEmitter=new ReleaseEmitter,this.noTokens=initFn===defaultInit,this.pauseFn=pauseFn,this.resumeFn=resumeFn,this.releaseEmitter.on("release",token=>{let p=this.waiting.shift();p?p.resolve(token):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.free.push(token))});for(let i=0;i<nr;i++)this.free.push(initFn())}async acquire(){let token=this.free.pop();return token||new Promise((resolve,reject)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn()),this.waiting.push({resolve,reject})})}async v(){return this.acquire()}release(token){this.releaseEmitter.emit("release",this.noTokens?"1":token)}p(token){return this.release(token)}drain(){let a=new Array(this.nrTokens);for(let i=0;i<this.nrTokens;i++)a[i]=this.acquire();return Promise.all(a)}nrWaiting(){return this.waiting.length}};Sema.prototype.v=util.deprecate(Sema.prototype.v,"`v()` is deperecated; use `acquire()` instead");Sema.prototype.p=util.deprecate(Sema.prototype.p,"`p()` is deprecated; use `release()` instead");module.exports=Sema}});function parseTeamRefs(args){let refs=[];for(let arg of args)for(let piece of arg.split(",")){let ref=piece.trim();ref&&!refs.includes(ref)&&refs.push(ref)}return refs}function teamRefBody(ref){return ref.startsWith("team_")?{teamId:ref}:{teamSlug:ref}}export{require_async_sema,parseTeamRefs,teamRefBody};
7
+ import{__commonJS,__require}from"./chunk-6L236MNA.js";var require_deque=__commonJS({"../../node_modules/.pnpm/double-ended-queue@2.1.0-0/node_modules/double-ended-queue/js/deque.js"(exports,module){"use strict";function Deque(capacity){if(this._capacity=getCapacity(capacity),this._length=0,this._front=0,isArray(capacity)){for(var len=capacity.length,i=0;i<len;++i)this[i]=capacity[i];this._length=len}}Deque.prototype.toArray=function(){for(var len=this._length,ret=new Array(len),front=this._front,capacity=this._capacity,j=0;j<len;++j)ret[j]=this[front+j&capacity-1];return ret};Deque.prototype.push=function(item){var argsLength=arguments.length,length=this._length;if(argsLength>1){var capacity=this._capacity;if(length+argsLength>capacity){for(var i=0;i<argsLength;++i){this._checkCapacity(length+1);var j=this._front+length&this._capacity-1;this[j]=arguments[i],length++,this._length=length}return length}else{for(var j=this._front,i=0;i<argsLength;++i)this[j+length&capacity-1]=arguments[i],j++;return this._length=length+argsLength,length+argsLength}}if(argsLength===0)return length;this._checkCapacity(length+1);var i=this._front+length&this._capacity-1;return this[i]=item,this._length=length+1,length+1};Deque.prototype.pop=function(){var length=this._length;if(length!==0){var i=this._front+length-1&this._capacity-1,ret=this[i];return this[i]=void 0,this._length=length-1,ret}};Deque.prototype.shift=function(){var length=this._length;if(length!==0){var front=this._front,ret=this[front];return this[front]=void 0,this._front=front+1&this._capacity-1,this._length=length-1,ret}};Deque.prototype.unshift=function(item){var length=this._length,argsLength=arguments.length;if(argsLength>1){var capacity=this._capacity;if(length+argsLength>capacity){for(var i=argsLength-1;i>=0;i--){this._checkCapacity(length+1);var capacity=this._capacity,j=(this._front-1&capacity-1^capacity)-capacity;this[j]=arguments[i],length++,this._length=length,this._front=j}return length}else{for(var front=this._front,i=argsLength-1;i>=0;i--){var j=(front-1&capacity-1^capacity)-capacity;this[j]=arguments[i],front=j}return this._front=front,this._length=length+argsLength,length+argsLength}}if(argsLength===0)return length;this._checkCapacity(length+1);var capacity=this._capacity,i=(this._front-1&capacity-1^capacity)-capacity;return this[i]=item,this._length=length+1,this._front=i,length+1};Deque.prototype.peekBack=function(){var length=this._length;if(length!==0){var index=this._front+length-1&this._capacity-1;return this[index]}};Deque.prototype.peekFront=function(){if(this._length!==0)return this[this._front]};Deque.prototype.get=function(index){var i=index;if(i===(i|0)){var len=this._length;if(i<0&&(i=i+len),!(i<0||i>=len))return this[this._front+i&this._capacity-1]}};Deque.prototype.isEmpty=function(){return this._length===0};Deque.prototype.clear=function(){for(var len=this._length,front=this._front,capacity=this._capacity,j=0;j<len;++j)this[front+j&capacity-1]=void 0;this._length=0,this._front=0};Deque.prototype.toString=function(){return this.toArray().toString()};Deque.prototype.valueOf=Deque.prototype.toString;Deque.prototype.removeFront=Deque.prototype.shift;Deque.prototype.removeBack=Deque.prototype.pop;Deque.prototype.insertFront=Deque.prototype.unshift;Deque.prototype.insertBack=Deque.prototype.push;Deque.prototype.enqueue=Deque.prototype.push;Deque.prototype.dequeue=Deque.prototype.shift;Deque.prototype.toJSON=Deque.prototype.toArray;Object.defineProperty(Deque.prototype,"length",{get:function(){return this._length},set:function(){throw new RangeError("")}});Deque.prototype._checkCapacity=function(size){this._capacity<size&&this._resizeTo(getCapacity(this._capacity*1.5+16))};Deque.prototype._resizeTo=function(capacity){var oldCapacity=this._capacity;this._capacity=capacity;var front=this._front,length=this._length;if(front+length>oldCapacity){var moveItemsCount=front+length&oldCapacity-1;arrayMove(this,0,this,oldCapacity,moveItemsCount)}};var isArray=Array.isArray;function arrayMove(src,srcIndex,dst,dstIndex,len){for(var j=0;j<len;++j)dst[j+dstIndex]=src[j+srcIndex],src[j+srcIndex]=void 0}function pow2AtLeast(n){return n=n>>>0,n=n-1,n=n|n>>1,n=n|n>>2,n=n|n>>4,n=n|n>>8,n=n|n>>16,n+1}function getCapacity(capacity){if(typeof capacity!="number")if(isArray(capacity))capacity=capacity.length;else return 16;return pow2AtLeast(Math.min(Math.max(16,capacity),1073741824))}module.exports=Deque}});var require_async_sema=__commonJS({"../../node_modules/.pnpm/async-sema@2.1.4/node_modules/async-sema/index.js"(exports,module){var EventEmitter=__require("events"),util=__require("util"),Deque=require_deque(),ReleaseEmitter=class extends EventEmitter{};function isFn(x){return typeof x=="function"}function defaultInit(){return"1"}var Sema=class{constructor(nr,{initFn=defaultInit,pauseFn,resumeFn,capacity=10}={}){if(isFn(pauseFn)^isFn(resumeFn))throw new Error("pauseFn and resumeFn must be both set for pausing");this.nrTokens=nr,this.free=new Deque(nr),this.waiting=new Deque(capacity),this.releaseEmitter=new ReleaseEmitter,this.noTokens=initFn===defaultInit,this.pauseFn=pauseFn,this.resumeFn=resumeFn,this.releaseEmitter.on("release",token=>{let p=this.waiting.shift();p?p.resolve(token):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.free.push(token))});for(let i=0;i<nr;i++)this.free.push(initFn())}async acquire(){let token=this.free.pop();return token||new Promise((resolve,reject)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn()),this.waiting.push({resolve,reject})})}async v(){return this.acquire()}release(token){this.releaseEmitter.emit("release",this.noTokens?"1":token)}p(token){return this.release(token)}drain(){let a=new Array(this.nrTokens);for(let i=0;i<this.nrTokens;i++)a[i]=this.acquire();return Promise.all(a)}nrWaiting(){return this.waiting.length}};Sema.prototype.v=util.deprecate(Sema.prototype.v,"`v()` is deperecated; use `acquire()` instead");Sema.prototype.p=util.deprecate(Sema.prototype.p,"`p()` is deprecated; use `release()` instead");module.exports=Sema}});export{require_async_sema};
@@ -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{formatOption,jsonOption,projectOption}from"./chunk-PV5YI2ZZ.js";import{packageName}from"./chunk-FI772UVH.js";var schemaSubcommand={name:"schema",aliases:[],description:"List available metrics or inspect a specific metric.",arguments:[{name:"metric-or-prefix",required:!1}],options:[formatOption,jsonOption],examples:[{name:"List all metrics",value:`${packageName} metrics schema`},{name:"Show metric details",value:`${packageName} metrics schema vercel.function_invocation`},{name:"Schema as JSON for agents",value:`${packageName} metrics schema vercel.request.count --json`}]},metricsCommand={name:"metrics",aliases:[],description:"Query observability metrics for your Vercel project or team.",arguments:[{name:"metric-id",required:!1}],subcommands:[{name:"query",aliases:[],description:"",default:!0,hidden:!0,arguments:[],options:[],examples:[]},schemaSubcommand],options:[{name:"aggregation",shorthand:"a",type:String,deprecated:!1,description:"Aggregation function (default: sum for counts/bytes/currency, avg for durations/memory/ratios)",argument:"FN"},{name:"group-by",shorthand:null,type:[String],deprecated:!1,description:"Dimensions to group by (repeatable)",argument:"DIM"},{name:"limit",shorthand:"l",type:Number,deprecated:!1,description:"Max groups per time bucket (default: 10)",argument:"N"},{name:"order-by",shorthand:null,type:String,deprecated:!1,description:"Order grouped results by value or count (default: count, or value when count is unsupported)",argument:"value|count"},{name:"order",shorthand:null,type:String,deprecated:!1,description:"Order direction for grouped results: asc or desc (default: desc)",argument:"asc|desc"},{name:"filter",shorthand:"f",type:[String],deprecated:!1,get description(){return process.env.FF_LEGACY_METRICS?"OData filter expression (repeatable, ANDed together)":"KQL filter expression (repeatable, ANDed together)"},argument:"EXPR"},{name:"prod",shorthand:null,type:Boolean,deprecated:!1,description:"Limit query to the production environment"},{name:"since",shorthand:"s",type:String,deprecated:!1,description:"Start time: relative (1h, 30m, 2d) or ISO date (default: 1h)",argument:"TIME"},{name:"until",shorthand:"u",type:String,deprecated:!1,description:"End time (default: now)",argument:"TIME"},{name:"granularity",shorthand:"g",type:String,deprecated:!1,description:"Time bucket size: 5m, 15m, 1h, 1d (default: auto)",argument:"SIZE"},{name:"bucket-timezone",shorthand:null,type:String,deprecated:!1,description:"IANA timezone for calendar bucket alignment only; does not shift --since/--until or output timestamps (e.g., Europe/Paris)",argument:"ZONE"},{...projectOption,shorthand:"p"},{name:"all",shorthand:null,type:Boolean,deprecated:!1,description:"Query across all projects for the team"},formatOption,jsonOption],get examples(){let canonical=!process.env.FF_LEGACY_METRICS,httpStatus=canonical?"httpStatus":"http_status",errorCode=canonical?"errorCode":"error_code",aiProvider=canonical?"aiProvider":"ai_provider",aiGatewayCostMetric=canonical?"vercel.ai_gateway.request.cost":"vercel.ai_gateway_request.cost",pageViewMetric=canonical?"vercel.analytics.page_view.count":"vercel.analytics_pageview.count",visitorId=canonical?"visitorId":"visitor_id",projectId=canonical?"projectId":"project_id",statusFilter=canonical?"httpStatus >= 500":"http_status ge 500",routeFilter=canonical?`'route:"/api"'`:`"contains(request_path, '/api')"`;return[{name:"5xx errors by error code in the last hour",value:`${packageName} metrics vercel.function_invocation.count -f "${statusFilter}" --group-by ${errorCode} --since 1h`},{name:"Function invocations by HTTP status code",value:`${packageName} metrics vercel.function_invocation.count --group-by ${httpStatus} --since 6h`},{name:"Function duration by route",value:`${packageName} metrics vercel.function_invocation.function_duration_ms -a avg --group-by route --since 1h`},{name:"AI Gateway costs by provider",value:`${packageName} metrics ${aiGatewayCostMetric} -a sum --group-by ${aiProvider} --since 7d`},{name:"Core Web Vitals (LCP) by route",value:`${packageName} metrics vercel.speed_insights.lcp_ms -a p75 --prod --group-by route --since 7d`},{name:"Routes with the lowest p75 LCP",value:`${packageName} metrics vercel.speed_insights.lcp_ms -a p75 --prod --group-by route --since 7d --order-by value --order asc`},{name:canonical?"Daily pageviews":"Daily pageviews with a Paris-aligned bucket",value:canonical?`${packageName} metrics ${pageViewMetric} --since 7d --granularity 1d`:`${packageName} metrics ${pageViewMetric} --since 7d --granularity 1d --bucket-timezone Europe/Paris`},{name:"Visitors time series from the top 5 countries",value:`${packageName} metrics ${pageViewMetric} -a unique/${visitorId} --group-by country --since 1d --granularity 1h --limit 5`},{name:"List available metrics",value:`${packageName} metrics schema`},{name:"Function executions matching an API route",value:`${packageName} metrics vercel.function_invocation.count -f ${routeFilter} --group-by route --since 1h`},{name:"Function executions matching multiple filters",value:`${packageName} metrics vercel.function_invocation.count -f "${statusFilter}" -f ${routeFilter} --since 1h`},{name:"Show schema for a metric prefix",value:`${packageName} metrics schema vercel.request`},{name:"Team-wide function executions by project",value:`${packageName} metrics --all vercel.function_invocation.count --group-by ${projectId} --since 24h`}]}};export{schemaSubcommand,metricsCommand};
7
+ import{formatOption,jsonOption,projectOption}from"./chunk-ROOWZCAB.js";import{packageName}from"./chunk-FI772UVH.js";var schemaSubcommand={name:"schema",aliases:[],description:"List available metrics or inspect a specific metric.",arguments:[{name:"metric-or-prefix",required:!1}],options:[formatOption,jsonOption],examples:[{name:"List all metrics",value:`${packageName} metrics schema`},{name:"Show metric details",value:`${packageName} metrics schema vercel.function_invocation`},{name:"Schema as JSON for agents",value:`${packageName} metrics schema vercel.request.count --json`}]},metricsCommand={name:"metrics",aliases:[],description:"Query observability metrics for your Vercel project or team.",arguments:[{name:"metric-id",required:!1}],subcommands:[{name:"query",aliases:[],description:"",default:!0,hidden:!0,arguments:[],options:[],examples:[]},schemaSubcommand],options:[{name:"aggregation",shorthand:"a",type:String,deprecated:!1,description:"Aggregation function (default: sum for counts/bytes/currency, avg for durations/memory/ratios)",argument:"FN"},{name:"group-by",shorthand:null,type:[String],deprecated:!1,description:"Dimensions to group by (repeatable)",argument:"DIM"},{name:"limit",shorthand:"l",type:Number,deprecated:!1,description:"Max groups per time bucket (default: 10)",argument:"N"},{name:"order-by",shorthand:null,type:String,deprecated:!1,description:"Order grouped results by value or count (default: count, or value when count is unsupported)",argument:"value|count"},{name:"order",shorthand:null,type:String,deprecated:!1,description:"Order direction for grouped results: asc or desc (default: desc)",argument:"asc|desc"},{name:"filter",shorthand:"f",type:[String],deprecated:!1,get description(){return process.env.FF_LEGACY_METRICS?"OData filter expression (repeatable, ANDed together)":"KQL filter expression (repeatable, ANDed together)"},argument:"EXPR"},{name:"prod",shorthand:null,type:Boolean,deprecated:!1,description:"Limit query to the production environment"},{name:"since",shorthand:"s",type:String,deprecated:!1,description:"Start time: relative (1h, 30m, 2d) or ISO date (default: 1h)",argument:"TIME"},{name:"until",shorthand:"u",type:String,deprecated:!1,description:"End time (default: now)",argument:"TIME"},{name:"granularity",shorthand:"g",type:String,deprecated:!1,description:"Time bucket size: 5m, 15m, 1h, 1d (default: auto)",argument:"SIZE"},{name:"bucket-timezone",shorthand:null,type:String,deprecated:!1,description:"IANA timezone for calendar bucket alignment only; does not shift --since/--until or output timestamps (e.g., Europe/Paris)",argument:"ZONE"},{...projectOption,shorthand:"p"},{name:"all",shorthand:null,type:Boolean,deprecated:!1,description:"Query across all projects for the team"},formatOption,jsonOption],get examples(){let canonical=!process.env.FF_LEGACY_METRICS,httpStatus=canonical?"httpStatus":"http_status",errorCode=canonical?"errorCode":"error_code",aiProvider=canonical?"aiProvider":"ai_provider",aiGatewayCostMetric=canonical?"vercel.ai_gateway.request.cost":"vercel.ai_gateway_request.cost",pageViewMetric=canonical?"vercel.analytics.page_view.count":"vercel.analytics_pageview.count",visitorId=canonical?"visitorId":"visitor_id",projectId=canonical?"projectId":"project_id",statusFilter=canonical?"httpStatus >= 500":"http_status ge 500",routeFilter=canonical?`'route:"/api"'`:`"contains(request_path, '/api')"`;return[{name:"5xx errors by error code in the last hour",value:`${packageName} metrics vercel.function_invocation.count -f "${statusFilter}" --group-by ${errorCode} --since 1h`},{name:"Function invocations by HTTP status code",value:`${packageName} metrics vercel.function_invocation.count --group-by ${httpStatus} --since 6h`},{name:"Function duration by route",value:`${packageName} metrics vercel.function_invocation.function_duration_ms -a avg --group-by route --since 1h`},{name:"AI Gateway costs by provider",value:`${packageName} metrics ${aiGatewayCostMetric} -a sum --group-by ${aiProvider} --since 7d`},{name:"Core Web Vitals (LCP) by route",value:`${packageName} metrics vercel.speed_insights.lcp_ms -a p75 --prod --group-by route --since 7d`},{name:"Routes with the lowest p75 LCP",value:`${packageName} metrics vercel.speed_insights.lcp_ms -a p75 --prod --group-by route --since 7d --order-by value --order asc`},{name:canonical?"Daily pageviews":"Daily pageviews with a Paris-aligned bucket",value:canonical?`${packageName} metrics ${pageViewMetric} --since 7d --granularity 1d`:`${packageName} metrics ${pageViewMetric} --since 7d --granularity 1d --bucket-timezone Europe/Paris`},{name:"Visitors time series from the top 5 countries",value:`${packageName} metrics ${pageViewMetric} -a unique/${visitorId} --group-by country --since 1d --granularity 1h --limit 5`},{name:"List available metrics",value:`${packageName} metrics schema`},{name:"Function executions matching an API route",value:`${packageName} metrics vercel.function_invocation.count -f ${routeFilter} --group-by route --since 1h`},{name:"Function executions matching multiple filters",value:`${packageName} metrics vercel.function_invocation.count -f "${statusFilter}" -f ${routeFilter} --since 1h`},{name:"Show schema for a metric prefix",value:`${packageName} metrics schema vercel.request`},{name:"Team-wide function executions by project",value:`${packageName} metrics --all vercel.function_invocation.count --group-by ${projectId} --since 24h`}]}};export{schemaSubcommand,metricsCommand};