vercel 64.2.0 → 64.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 (175) hide show
  1. package/dist/chunks/{add-WVK3AP46.js → add-5RV75RPG.js} +1 -1
  2. package/dist/chunks/{add-UPXURHDI.js → add-FRVZLYB5.js} +1 -1
  3. package/dist/chunks/{add-IATD2WUV.js → add-UXOTAL3N.js} +1 -1
  4. package/dist/chunks/{build-JOGD3ZEF.js → build-F5GOX2EV.js} +1 -1
  5. package/dist/chunks/{chunk-XEQT373M.js → chunk-2B3A3MOX.js} +1 -1
  6. package/dist/chunks/{chunk-4VEK7DEH.js → chunk-444RE4Z5.js} +1 -1
  7. package/dist/chunks/{chunk-TY4PMK7Y.js → chunk-6GIP2YPX.js} +1 -1
  8. package/dist/chunks/{chunk-KLYIX4HK.js → chunk-6HOVHRWJ.js} +3 -3
  9. package/dist/chunks/{chunk-IRJ5XFT2.js → chunk-6RVMAWKT.js} +2 -2
  10. package/dist/chunks/chunk-6ZRULOO3.js +7 -0
  11. package/dist/chunks/{chunk-JGPRCZC2.js → chunk-7GFRZWLE.js} +1 -1
  12. package/dist/chunks/{chunk-CN3IVZJO.js → chunk-7NNENHGN.js} +1 -1
  13. package/dist/chunks/{chunk-VURCIZKT.js → chunk-A63VVXW2.js} +1 -1
  14. package/dist/chunks/{chunk-4IIRQJUW.js → chunk-AA434KXY.js} +1 -1
  15. package/dist/chunks/{chunk-N5D4455C.js → chunk-AALI66ML.js} +1 -1
  16. package/dist/chunks/{chunk-AKM22FBX.js → chunk-AQUDXMFH.js} +1 -1
  17. package/dist/chunks/chunk-BAT6SDBJ.js +10 -0
  18. package/dist/chunks/chunk-BFRDBBSO.js +7 -0
  19. package/dist/chunks/{chunk-WE3ZJX7P.js → chunk-CMKLX4DC.js} +1 -1
  20. package/dist/chunks/{chunk-JSBEAHKA.js → chunk-CYV3X62I.js} +1 -1
  21. package/dist/chunks/{chunk-EO7GUARB.js → chunk-DNDBPLLI.js} +1 -1
  22. package/dist/chunks/{chunk-UJUNGWSD.js → chunk-DNTQK2SW.js} +1 -1
  23. package/dist/chunks/{chunk-4BS552UW.js → chunk-DWEDXCBK.js} +2 -2
  24. package/dist/chunks/{chunk-3GSGG4YR.js → chunk-E6R2QOOR.js} +1 -1
  25. package/dist/chunks/{chunk-CRQDQNQZ.js → chunk-ELDHGU6N.js} +1 -1
  26. package/dist/chunks/{chunk-DYQXJCHO.js → chunk-EVQJ7SCV.js} +1 -1
  27. package/dist/chunks/{chunk-FTY4BCAF.js → chunk-EXPLBM7J.js} +1 -1
  28. package/dist/chunks/{chunk-YO4VLAB7.js → chunk-FLBI6DY2.js} +1 -1
  29. package/dist/chunks/{chunk-N6ECEBHG.js → chunk-G2IJOQR3.js} +1 -1
  30. package/dist/chunks/{chunk-5JEU6QSM.js → chunk-GCSAJUL6.js} +1 -1
  31. package/dist/chunks/{chunk-OLWE4UFC.js → chunk-GF7EG5IA.js} +1 -1
  32. package/dist/chunks/{chunk-NBABZO3A.js → chunk-GJP22N6R.js} +1 -1
  33. package/dist/chunks/{chunk-YDM2PMMP.js → chunk-GLJH35MJ.js} +1 -1
  34. package/dist/chunks/{chunk-TBLIJ2PS.js → chunk-GNV6PG6W.js} +1 -1
  35. package/dist/chunks/{chunk-FGNMYSLD.js → chunk-GWZ4VPU3.js} +1 -1
  36. package/dist/chunks/{chunk-4GL254L4.js → chunk-H3KYG32S.js} +2 -2
  37. package/dist/chunks/{chunk-JEPRHNQU.js → chunk-HJRAWEA2.js} +1 -1
  38. package/dist/chunks/{chunk-7BOCT55A.js → chunk-HTLGLTKD.js} +2 -2
  39. package/dist/chunks/{chunk-E6UKNYFF.js → chunk-HVUJNVPS.js} +1 -1
  40. package/dist/chunks/{chunk-WZ7YJDKT.js → chunk-IIC2A4YN.js} +1 -1
  41. package/dist/chunks/{chunk-N7Q2IESO.js → chunk-IJCCFLCQ.js} +1 -1
  42. package/dist/chunks/{chunk-KUGY5FIM.js → chunk-IL7X6EKK.js} +1 -1
  43. package/dist/chunks/{chunk-XD2LZRBS.js → chunk-IQ7FPAI4.js} +1 -1
  44. package/dist/chunks/{chunk-J2LAZELI.js → chunk-IVIZLWZQ.js} +1 -1
  45. package/dist/chunks/{chunk-O7JMHULU.js → chunk-IYCHAIFZ.js} +1 -1
  46. package/dist/chunks/{chunk-TWKII7HO.js → chunk-JCTXRR4A.js} +1 -1
  47. package/dist/chunks/{chunk-GSVOI5LW.js → chunk-JV6IPUGX.js} +1 -1
  48. package/dist/chunks/{chunk-GSOPJJO5.js → chunk-KKCBFBJK.js} +1 -1
  49. package/dist/chunks/{chunk-WVJYKHGZ.js → chunk-KKQL4AKH.js} +1 -1
  50. package/dist/chunks/{chunk-JNJOUMGF.js → chunk-KUGXOLL7.js} +1 -1
  51. package/dist/chunks/{chunk-75IAMKGV.js → chunk-M774HRX5.js} +2 -2
  52. package/dist/chunks/{chunk-J3CDVZE7.js → chunk-MMPQC2N6.js} +1 -1
  53. package/dist/chunks/{chunk-PAN6TUTQ.js → chunk-MV4WHUIC.js} +1 -1
  54. package/dist/chunks/{chunk-SYEKOJHT.js → chunk-MZ3QGJH3.js} +1 -1
  55. package/dist/chunks/{chunk-QDOYNWNQ.js → chunk-MZLQY2EQ.js} +1 -1
  56. package/dist/chunks/chunk-NLCTF4EJ.js +14 -0
  57. package/dist/chunks/{chunk-SQB4T5FL.js → chunk-OCOVCC5Q.js} +1 -1
  58. package/dist/chunks/{chunk-ZUCSA4IW.js → chunk-OJKZ7EV3.js} +1 -1
  59. package/dist/chunks/{chunk-7C6BXZCV.js → chunk-OUTCLR64.js} +1 -1
  60. package/dist/chunks/{chunk-WIAAACUI.js → chunk-OXAPCSYY.js} +1 -1
  61. package/dist/chunks/{chunk-3EU7MN5M.js → chunk-QAETJRKX.js} +1 -1
  62. package/dist/chunks/{chunk-WW4VUFHJ.js → chunk-QC3HEGFD.js} +1 -1
  63. package/dist/chunks/{chunk-YBOS65VB.js → chunk-QC5AMRWR.js} +1 -1
  64. package/dist/chunks/{chunk-LLPIBKFX.js → chunk-QCWV7FML.js} +1 -1
  65. package/dist/chunks/{chunk-XSVF2CZM.js → chunk-TCYAAWLB.js} +1 -1
  66. package/dist/chunks/{chunk-THZR6O2M.js → chunk-TDDZGUU6.js} +1 -1
  67. package/dist/chunks/{chunk-4TTF5E5U.js → chunk-U3NQZJQ4.js} +8 -8
  68. package/dist/chunks/{chunk-BTCKMXWW.js → chunk-UQIVF4Q2.js} +1 -1
  69. package/dist/chunks/{chunk-X65QKYDM.js → chunk-VRWLNWNE.js} +1 -1
  70. package/dist/chunks/{chunk-QL3IYPBV.js → chunk-WGOQGKS5.js} +1 -1
  71. package/dist/chunks/{chunk-3EYOQC4R.js → chunk-WYI4VNXT.js} +1 -1
  72. package/dist/chunks/{chunk-SRAC7DI4.js → chunk-XJXX4QXA.js} +1 -1
  73. package/dist/chunks/{chunk-YIIPBH2D.js → chunk-XSDAUM4F.js} +1 -1
  74. package/dist/chunks/{chunk-GUJVJKO7.js → chunk-XW4ZWX3I.js} +1 -1
  75. package/dist/chunks/chunk-XXCWQPAH.js +7 -0
  76. package/dist/chunks/{chunk-A5R2HHNK.js → chunk-YROIQRYI.js} +1 -1
  77. package/dist/chunks/{chunk-YP46QVEI.js → chunk-YS542RHZ.js} +1 -1
  78. package/dist/chunks/{chunk-SGXN7SMU.js → chunk-ZLWTPS5T.js} +1 -1
  79. package/dist/chunks/{chunk-5UEBA6N6.js → chunk-ZQKDO5PL.js} +1 -1
  80. package/dist/chunks/{chunk-WPQN5UKR.js → chunk-ZQME5XUJ.js} +1 -1
  81. package/dist/chunks/{chunk-EF3YL2R7.js → chunk-ZVLDGT4O.js} +1 -1
  82. package/dist/chunks/{chunk-I62UUYTS.js → chunk-ZVTI6BRR.js} +1 -1
  83. package/dist/chunks/{chunk-N7L3XLWC.js → chunk-ZZ3LJ22B.js} +1 -1
  84. package/dist/chunks/{clear-FNH7KUCF.js → clear-2VHJFFMM.js} +1 -1
  85. package/dist/chunks/{compile-vercel-config-4LNHE3YV.js → compile-vercel-config-ADKZDUAU.js} +1 -1
  86. package/dist/chunks/{config-JEHKUQMZ.js → config-AZ2O2E4R.js} +1 -1
  87. package/dist/chunks/{config-W3TVZPSK.js → config-D22GD5IM.js} +1 -1
  88. package/dist/chunks/{connect-git-provider-VJYXBRYG.js → connect-git-provider-2JIBL3ST.js} +1 -1
  89. package/dist/chunks/{delete-HCZA6EVL.js → delete-4JCBFL7Y.js} +1 -1
  90. package/dist/chunks/{delete-LV744KVD.js → delete-UOY7IFZV.js} +1 -1
  91. package/dist/chunks/{detect-services-TVZ4HYVB.js → detect-services-A2B6KJO5.js} +1 -1
  92. package/dist/chunks/{disable-N7WZSMD4.js → disable-Q5BTSVR7.js} +1 -1
  93. package/dist/chunks/{discard-2DN52DNW.js → discard-5LQP6CPX.js} +1 -1
  94. package/dist/chunks/edit-3XGKBSUZ.js +9 -0
  95. package/dist/chunks/edit-R5X24DJJ.js +8 -0
  96. package/dist/chunks/{enable-7GKPLJNR.js → enable-V2IPH6TD.js} +1 -1
  97. package/dist/chunks/{exec-QZXH5RXR.js → exec-NMRO6DIZ.js} +2 -2
  98. package/dist/chunks/{export-BSOJAVDV.js → export-WLJE6AJW.js} +1 -1
  99. package/dist/chunks/{future-OV5I5HWT.js → future-6UTK4EFE.js} +1 -1
  100. package/dist/chunks/{generate-cert-for-deploy-GKQRQ3ZQ.js → generate-cert-for-deploy-WDKFR34X.js} +1 -1
  101. package/dist/chunks/{image-NMQWZBTW.js → image-IL7IN7MD.js} +1 -1
  102. package/dist/chunks/{import-builders-WLKZNPTB.js → import-builders-FX2XXVRT.js} +1 -1
  103. package/dist/chunks/{inspect-PV6VVAN6.js → inspect-DZMXSBMA.js} +1 -1
  104. package/dist/chunks/{inspect-LZJ5X3PH.js → inspect-E2HPGMNI.js} +1 -1
  105. package/dist/chunks/{inspect-V7M3GSZ7.js → inspect-F6NLCWHN.js} +1 -1
  106. package/dist/chunks/{inspect-LF3DIZZ2.js → inspect-UNZR445S.js} +1 -1
  107. package/dist/chunks/{inspect-UEDFNY5H.js → inspect-VVYQWFTM.js} +1 -1
  108. package/dist/chunks/{list-AFVTD43R.js → list-DXOVBT4F.js} +1 -1
  109. package/dist/chunks/{list-64R2DNZA.js → list-G4E6RG3V.js} +1 -1
  110. package/dist/chunks/{list-QTTCSTZA.js → list-GDI5O246.js} +1 -1
  111. package/dist/chunks/{login-OS6DZT32.js → login-HU5OFS7T.js} +1 -1
  112. package/dist/chunks/{login-SKIDVUB7.js → login-XPUGYRGM.js} +1 -1
  113. package/dist/chunks/{logs-6AXWBF4D.js → logs-EWXTZN4W.js} +1 -1
  114. package/dist/chunks/{ls-WSPWJDWP.js → ls-3GNX6IPE.js} +1 -1
  115. package/dist/chunks/{ls-5TZIOB3Q.js → ls-A3HIPTF5.js} +1 -1
  116. package/dist/chunks/{ls-EADWIBEQ.js → ls-A4NEYMKP.js} +1 -1
  117. package/dist/chunks/{ls-UP6KDPCD.js → ls-CGZ3NL5R.js} +1 -1
  118. package/dist/chunks/{ls-723HTK5U.js → ls-PF2XG6UU.js} +1 -1
  119. package/dist/chunks/{ls-YPQ3CTTN.js → ls-SZKDUJHV.js} +1 -1
  120. package/dist/chunks/{ls-A5A3APRI.js → ls-TCB7UUPP.js} +1 -1
  121. package/dist/chunks/{mutate-WHVA5NTT.js → mutate-BQAP2S7A.js} +1 -1
  122. package/dist/chunks/notifications-WUCV63TE.js +7 -0
  123. package/dist/chunks/{open-SV3USET3.js → open-QJE5QER2.js} +1 -1
  124. package/dist/chunks/{openapi-NZJ6Q5Y2.js → openapi-BQSQNXQE.js} +1 -1
  125. package/dist/chunks/{permissions-3ZMQVJAQ.js → permissions-6LOJKL5W.js} +1 -1
  126. package/dist/chunks/{prompt-missing-credentials-44DQQXOI.js → prompt-missing-credentials-IGTCFUA6.js} +1 -1
  127. package/dist/chunks/{publish-EDLEZCAF.js → publish-XR24NSTQ.js} +1 -1
  128. package/dist/chunks/pull-CXUNHWAO.js +7 -0
  129. package/dist/chunks/{purchase-domain-if-available-R3YQ2TFP.js → purchase-domain-if-available-4YKWAHH5.js} +1 -1
  130. package/dist/chunks/{push-6O3JAFDA.js → push-YOAY5F5X.js} +1 -1
  131. package/dist/chunks/{query-MYKQOBG3.js → query-GHFOZV7K.js} +1 -1
  132. package/dist/chunks/{reauthenticate-3UH4WWKC.js → reauthenticate-W7QIXLZ3.js} +1 -1
  133. package/dist/chunks/{reorder-IU6GZK4H.js → reorder-TQGSMCBZ.js} +1 -1
  134. package/dist/chunks/{reply-FG74YRJ3.js → reply-G4EVGJQ3.js} +1 -1
  135. package/dist/chunks/{resolve-MD3PGOME.js → resolve-SNM6MK5J.js} +1 -1
  136. package/dist/chunks/{resolve-agent-team-X6GPGGDR.js → resolve-agent-team-43HZCPF3.js} +1 -1
  137. package/dist/chunks/{restore-7KOACNT7.js → restore-3NDP224I.js} +1 -1
  138. package/dist/chunks/{rm-JRAF4TPV.js → rm-2TR2KBDP.js} +1 -1
  139. package/dist/chunks/{rm-SKKBN7LZ.js → rm-IGY6LD6H.js} +1 -1
  140. package/dist/chunks/{rm-HOE3GJAB.js → rm-N6ZUA66Z.js} +1 -1
  141. package/dist/chunks/{rm-CSIBWFYG.js → rm-OI5VS7GG.js} +1 -1
  142. package/dist/chunks/{rm-ZF2F2ZE3.js → rm-REZG7TP4.js} +1 -1
  143. package/dist/chunks/{routes-3RJGIZYJ.js → routes-LK2HUGAK.js} +1 -1
  144. package/dist/chunks/{rule-inspect-NICYVQPY.js → rule-inspect-NLEABBTP.js} +1 -1
  145. package/dist/chunks/{rules-NHACEVVC.js → rules-XSLHADBV.js} +1 -1
  146. package/dist/chunks/{schema-3XLZGVH5.js → schema-HWS2SOZS.js} +1 -1
  147. package/dist/chunks/{schema-ZJASGDRI.js → schema-KG4RWQBC.js} +1 -1
  148. package/dist/chunks/{select-org-XVAGUP4V.js → select-org-AAB5RBSB.js} +1 -1
  149. package/dist/chunks/{set-JOSIBICX.js → set-AJEMEBZU.js} +1 -1
  150. package/dist/chunks/setup-and-link-6AIRWXXX.js +7 -0
  151. package/dist/chunks/{tags-LVP4LVHL.js → tags-O6R6VWPP.js} +1 -1
  152. package/dist/chunks/{types-YEYQERHE.js → types-Y3NJROKH.js} +1 -1
  153. package/dist/chunks/{update-HPEVXFST.js → update-C7XR7CHI.js} +1 -1
  154. package/dist/commands/build/index.js +1 -1
  155. package/dist/commands/deploy/index.js +13 -13
  156. package/dist/commands/dev/index.js +2 -2
  157. package/dist/commands/env/index.js +1 -1
  158. package/dist/commands/link/index.js +1 -1
  159. package/dist/commands/list/index.js +1 -1
  160. package/dist/commands-bulk.js +760 -708
  161. package/dist/index.js +2 -2
  162. package/dist/internal-build.js +1 -1
  163. package/dist/root-help-commands.mjs +1 -1
  164. package/dist/version.mjs +1 -1
  165. package/package.json +56 -55
  166. package/dist/chunks/chunk-2FHICLHJ.js +0 -7
  167. package/dist/chunks/chunk-EEZLBOSP.js +0 -14
  168. package/dist/chunks/chunk-EKUHN42H.js +0 -7
  169. package/dist/chunks/chunk-HAVEFTOO.js +0 -7
  170. package/dist/chunks/chunk-RIDPB64C.js +0 -10
  171. package/dist/chunks/edit-CALU7PMG.js +0 -8
  172. package/dist/chunks/edit-MGJWXNFV.js +0 -9
  173. package/dist/chunks/notifications-I4PKIOYY.js +0 -7
  174. package/dist/chunks/pull-5DQNSJCA.js +0 -7
  175. package/dist/chunks/setup-and-link-7GIAMCTM.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{displayDetectedServices,readConfig,setupAndLink}from"../../chunks/chunk-WW4VUFHJ.js";import{loadVercelConfig,tryDetectServices}from"../../chunks/chunk-7C6BXZCV.js";import"../../chunks/chunk-YTEZO2SZ.js";import{FIX_BY_CODE,createErrorReporter,import_write_build_result,require_detect_builders_with_services,require_get_files,require_mime_types,require_schedule_entrypoint,require_service_schedules,toDiagnostic}from"../../chunks/chunk-NBABZO3A.js";import{importBuilders,require_npa}from"../../chunks/chunk-XSVF2CZM.js";import"../../chunks/chunk-4CACOKMS.js";import"../../chunks/chunk-COD3WAUI.js";import{LOCAL_SCHEDULES_SESSION_HEADER,createLocalSchedulesSession}from"../../chunks/chunk-SF4E3AQ3.js";import"../../chunks/chunk-TWKII7HO.js";import"../../chunks/chunk-QHJLRTVY.js";import{require_fast_deep_equal}from"../../chunks/chunk-MCRKBVZA.js";import{getUpdateCommand}from"../../chunks/chunk-J3CDVZE7.js";import{readJSONFile}from"../../chunks/chunk-QDOYNWNQ.js";import"../../chunks/chunk-4VEK7DEH.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-WVJYKHGZ.js";import{validateConfig}from"../../chunks/chunk-YBOS65VB.js";import"../../chunks/chunk-XD2LZRBS.js";import"../../chunks/chunk-SYEKOJHT.js";import"../../chunks/chunk-EAUDC24V.js";import{pickOverrides}from"../../chunks/chunk-TY4PMK7Y.js";import{require_dist as require_dist5}from"../../chunks/chunk-FGNMYSLD.js";import{require_brace_expansion,require_dist as require_dist3,require_dist2 as require_dist4,require_minimatch}from"../../chunks/chunk-BLAIBYEU.js";import{require_main}from"../../chunks/chunk-SQB4T5FL.js";import"../../chunks/chunk-RRDNKB2X.js";import"../../chunks/chunk-MVGTMPMI.js";import"../../chunks/chunk-SACGQMVQ.js";import"../../chunks/chunk-BPUANOGW.js";import"../../chunks/chunk-3E364MJE.js";import{require_inherits}from"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-P2O5DOYE.js";import"../../chunks/chunk-GSOPJJO5.js";import{VERCEL_OIDC_TOKEN}from"../../chunks/chunk-SRAC7DI4.js";import"../../chunks/chunk-EKUHN42H.js";import{require_json_parse_better_errors}from"../../chunks/chunk-25565AGS.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-J24BABG4.js";import{pullEnvRecords}from"../../chunks/chunk-YP46QVEI.js";import{printProjectNotFoundError}from"../../chunks/chunk-5JEU6QSM.js";import"../../chunks/chunk-3GSGG4YR.js";import"../../chunks/chunk-PVASGBEF.js";import{require_frameworks}from"../../chunks/chunk-MVCAUS4F.js";import{DEV_QUEUE_API_PREFIX,DEV_QUEUE_DEFAULT_PORT,DEV_QUEUE_PROXY_PREFIX,DEV_RESOURCE_TOKEN,DEV_RUNTIME_CACHE_DEFAULT_PORT,DEV_SCHEDULES_DEFAULT_PORT,DEV_SCHEDULES_PROXY_PREFIX,devCommand,getDevQueueEnv,getDevSchedulesEnv,isValidDevResourceHost,listenOnDevResourcePort}from"../../chunks/chunk-TPVAPVQC.js";import{require_dist as require_dist2}from"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-WE3ZJX7P.js";import"../../chunks/chunk-DYQXJCHO.js";import"../../chunks/chunk-SCV7XEEO.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-3EYOQC4R.js";import"../../chunks/chunk-XEQT373M.js";import"../../chunks/chunk-J2LAZELI.js";import"../../chunks/chunk-E6UKNYFF.js";import{help}from"../../chunks/chunk-4GL254L4.js";import"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-3EU7MN5M.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{detectExplicitScope,getLocalPathConfig,highlight}from"../../chunks/chunk-WZ7YJDKT.js";import{TelemetryClient}from"../../chunks/chunk-JNJOUMGF.js";import{getGlobalPathConfig}from"../../chunks/chunk-PAN6TUTQ.js";import"../../chunks/chunk-VKXEOL4K.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{isNativeBinaryInstall}from"../../chunks/chunk-NWGBDBZI.js";import"../../chunks/chunk-4SAVH3H7.js";import"../../chunks/chunk-ZS2WS4AM.js";import"../../chunks/chunk-AOWWC6WZ.js";import{directFetch}from"../../chunks/chunk-MY4MONOH.js";import{parseArguments}from"../../chunks/chunk-CRQDQNQZ.js";import{buildCommandWithYes,outputActionRequired}from"../../chunks/chunk-RIDPB64C.js";import{getFlagsSpecification}from"../../chunks/chunk-MI7W4QMV.js";import{VERCEL_DIR,findRepoRoot,getLinkedProject,getVercelDirectory,require_lib,require_pluralize,resolveProjectCwd}from"../../chunks/chunk-4TTF5E5U.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import{printAlignedLabel}from"../../chunks/chunk-N7Q2IESO.js";import"../../chunks/chunk-WPQN5UKR.js";import"../../chunks/chunk-2VBFQZ72.js";import{CantParseJSONFile,LambdaSizeExceededError,MissingDotenvVarsError,NowError,require_bytes}from"../../chunks/chunk-YIIPBH2D.js";import{cmd,getCommandName,getCommandNamePlain,getTitleName}from"../../chunks/chunk-JESNVRVR.js";import{Diagnostic,defineDiagnostics,init_dist,link_default,output_manager_default,require_build_utils}from"../../chunks/chunk-75IAMKGV.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import{pkg_default}from"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import{require_supports_color}from"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__commonJS,__require,__toESM}from"../../chunks/chunk-BZENIQ7N.js";var require_bytes2=__commonJS({"../../node_modules/.pnpm/bytes@3.1.0/node_modules/bytes/index.js"(exports2,module2){"use strict";module2.exports=bytes2;module2.exports.format=format;module2.exports.parse=parse2;var formatThousandsRegExp=/\B(?=(\d{3})+(?!\d))/g,formatDecimalsRegExp=/(?:\.0*|(\.[^0]+)0+)$/,map={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},parseRegExp=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function bytes2(value,options){return typeof value=="string"?parse2(value):typeof value=="number"?format(value,options):null}function format(value,options){if(!Number.isFinite(value))return null;var mag=Math.abs(value),thousandsSeparator=options&&options.thousandsSeparator||"",unitSeparator=options&&options.unitSeparator||"",decimalPlaces=options&&options.decimalPlaces!==void 0?options.decimalPlaces:2,fixedDecimals=!!(options&&options.fixedDecimals),unit=options&&options.unit||"";(!unit||!map[unit.toLowerCase()])&&(mag>=map.pb?unit="PB":mag>=map.tb?unit="TB":mag>=map.gb?unit="GB":mag>=map.mb?unit="MB":mag>=map.kb?unit="KB":unit="B");var val=value/map[unit.toLowerCase()],str=val.toFixed(decimalPlaces);return fixedDecimals||(str=str.replace(formatDecimalsRegExp,"$1")),thousandsSeparator&&(str=str.replace(formatThousandsRegExp,thousandsSeparator)),str+unitSeparator+unit}function parse2(val){if(typeof val=="number"&&!isNaN(val))return val;if(typeof val!="string")return null;var results=parseRegExp.exec(val),floatValue,unit="b";return results?(floatValue=parseFloat(results[1]),unit=results[4].toLowerCase()):(floatValue=parseInt(val,10),unit="b"),Math.floor(map[unit]*floatValue)}}});var require_callsite_tostring=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/lib/compat/callsite-tostring.js"(exports2,module2){"use strict";module2.exports=callSiteToString2;function callSiteFileLocation(callSite){var fileName,fileLocation="";if(callSite.isNative()?fileLocation="native":callSite.isEval()?(fileName=callSite.getScriptNameOrSourceURL(),fileName||(fileLocation=callSite.getEvalOrigin())):fileName=callSite.getFileName(),fileName){fileLocation+=fileName;var lineNumber=callSite.getLineNumber();if(lineNumber!=null){fileLocation+=":"+lineNumber;var columnNumber=callSite.getColumnNumber();columnNumber&&(fileLocation+=":"+columnNumber)}}return fileLocation||"unknown source"}function callSiteToString2(callSite){var addSuffix=!0,fileLocation=callSiteFileLocation(callSite),functionName=callSite.getFunctionName(),isConstructor=callSite.isConstructor(),isMethodCall=!(callSite.isToplevel()||isConstructor),line="";if(isMethodCall){var methodName=callSite.getMethodName(),typeName=getConstructorName(callSite);functionName?(typeName&&functionName.indexOf(typeName)!==0&&(line+=typeName+"."),line+=functionName,methodName&&functionName.lastIndexOf("."+methodName)!==functionName.length-methodName.length-1&&(line+=" [as "+methodName+"]")):line+=typeName+"."+(methodName||"<anonymous>")}else isConstructor?line+="new "+(functionName||"<anonymous>"):functionName?line+=functionName:(addSuffix=!1,line+=fileLocation);return addSuffix&&(line+=" ("+fileLocation+")"),line}function getConstructorName(obj){var receiver=obj.receiver;return receiver.constructor&&receiver.constructor.name||null}}});var require_event_listener_count=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/lib/compat/event-listener-count.js"(exports2,module2){"use strict";module2.exports=eventListenerCount2;function eventListenerCount2(emitter,type){return emitter.listeners(type).length}}});var require_compat=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/lib/compat/index.js"(exports2,module2){"use strict";var EventEmitter=__require("events").EventEmitter;lazyProperty(module2.exports,"callSiteToString",function(){var limit=Error.stackTraceLimit,obj={},prep=Error.prepareStackTrace;function prepareObjectStackTrace2(obj2,stack3){return stack3}Error.prepareStackTrace=prepareObjectStackTrace2,Error.stackTraceLimit=2,Error.captureStackTrace(obj);var stack2=obj.stack.slice();return Error.prepareStackTrace=prep,Error.stackTraceLimit=limit,stack2[0].toString?toString:require_callsite_tostring()});lazyProperty(module2.exports,"eventListenerCount",function(){return EventEmitter.listenerCount||require_event_listener_count()});function lazyProperty(obj,prop,getter){function get(){var val=getter();return Object.defineProperty(obj,prop,{configurable:!0,enumerable:!0,value:val}),val}Object.defineProperty(obj,prop,{configurable:!0,enumerable:!0,get})}function toString(obj){return obj.toString()}}});var require_depd=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/index.js"(exports,module){var callSiteToString=require_compat().callSiteToString,eventListenerCount=require_compat().eventListenerCount,relative=__require("path").relative;module.exports=depd;var basePath=process.cwd();function containsNamespace(str,namespace){for(var vals=str.split(/[ ,]+/),ns=String(namespace).toLowerCase(),i=0;i<vals.length;i++){var val=vals[i];if(val&&(val==="*"||val.toLowerCase()===ns))return!0}return!1}function convertDataDescriptorToAccessor(obj,prop,message2){var descriptor=Object.getOwnPropertyDescriptor(obj,prop),value=descriptor.value;return descriptor.get=function(){return value},descriptor.writable&&(descriptor.set=function(val){return value=val}),delete descriptor.value,delete descriptor.writable,Object.defineProperty(obj,prop,descriptor),descriptor}function createArgumentsString(arity){for(var str="",i=0;i<arity;i++)str+=", arg"+i;return str.substr(2)}function createStackString(stack2){var str=this.name+": "+this.namespace;this.message&&(str+=" deprecated "+this.message);for(var i=0;i<stack2.length;i++)str+=`
7
+ import{displayDetectedServices,readConfig,setupAndLink}from"../../chunks/chunk-QC3HEGFD.js";import{loadVercelConfig,tryDetectServices}from"../../chunks/chunk-OUTCLR64.js";import"../../chunks/chunk-YTEZO2SZ.js";import{FIX_BY_CODE,createErrorReporter,import_write_build_result,require_detect_builders_with_services,require_get_files,require_mime_types,require_schedule_entrypoint,require_service_schedules,toDiagnostic}from"../../chunks/chunk-GJP22N6R.js";import{importBuilders,require_npa}from"../../chunks/chunk-TCYAAWLB.js";import"../../chunks/chunk-4CACOKMS.js";import"../../chunks/chunk-COD3WAUI.js";import{LOCAL_SCHEDULES_SESSION_HEADER,createLocalSchedulesSession}from"../../chunks/chunk-SF4E3AQ3.js";import"../../chunks/chunk-JCTXRR4A.js";import"../../chunks/chunk-QHJLRTVY.js";import{require_fast_deep_equal}from"../../chunks/chunk-MCRKBVZA.js";import{getUpdateCommand}from"../../chunks/chunk-MMPQC2N6.js";import{readJSONFile}from"../../chunks/chunk-MZLQY2EQ.js";import"../../chunks/chunk-444RE4Z5.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-KKQL4AKH.js";import{validateConfig}from"../../chunks/chunk-QC5AMRWR.js";import"../../chunks/chunk-IQ7FPAI4.js";import"../../chunks/chunk-MZ3QGJH3.js";import"../../chunks/chunk-EAUDC24V.js";import{pickOverrides}from"../../chunks/chunk-6GIP2YPX.js";import{require_dist as require_dist5}from"../../chunks/chunk-GWZ4VPU3.js";import{require_brace_expansion,require_dist as require_dist3,require_dist2 as require_dist4,require_minimatch}from"../../chunks/chunk-BLAIBYEU.js";import{require_main}from"../../chunks/chunk-OCOVCC5Q.js";import"../../chunks/chunk-RRDNKB2X.js";import"../../chunks/chunk-MVGTMPMI.js";import"../../chunks/chunk-SACGQMVQ.js";import"../../chunks/chunk-BPUANOGW.js";import"../../chunks/chunk-3E364MJE.js";import{require_inherits}from"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-P2O5DOYE.js";import"../../chunks/chunk-KKCBFBJK.js";import{VERCEL_OIDC_TOKEN}from"../../chunks/chunk-XJXX4QXA.js";import"../../chunks/chunk-6ZRULOO3.js";import{require_json_parse_better_errors}from"../../chunks/chunk-25565AGS.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-J24BABG4.js";import{pullEnvRecords}from"../../chunks/chunk-YS542RHZ.js";import{printProjectNotFoundError}from"../../chunks/chunk-GCSAJUL6.js";import"../../chunks/chunk-E6R2QOOR.js";import"../../chunks/chunk-PVASGBEF.js";import{require_frameworks}from"../../chunks/chunk-MVCAUS4F.js";import{DEV_QUEUE_API_PREFIX,DEV_QUEUE_DEFAULT_PORT,DEV_QUEUE_PROXY_PREFIX,DEV_RESOURCE_TOKEN,DEV_RUNTIME_CACHE_DEFAULT_PORT,DEV_SCHEDULES_DEFAULT_PORT,DEV_SCHEDULES_PROXY_PREFIX,devCommand,getDevQueueEnv,getDevSchedulesEnv,isValidDevResourceHost,listenOnDevResourcePort}from"../../chunks/chunk-TPVAPVQC.js";import{require_dist as require_dist2}from"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-CMKLX4DC.js";import"../../chunks/chunk-EVQJ7SCV.js";import"../../chunks/chunk-SCV7XEEO.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-WYI4VNXT.js";import"../../chunks/chunk-2B3A3MOX.js";import"../../chunks/chunk-IVIZLWZQ.js";import"../../chunks/chunk-HVUJNVPS.js";import{help}from"../../chunks/chunk-H3KYG32S.js";import"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-QAETJRKX.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{detectExplicitScope,getLocalPathConfig,highlight}from"../../chunks/chunk-IIC2A4YN.js";import{TelemetryClient}from"../../chunks/chunk-KUGXOLL7.js";import{getGlobalPathConfig}from"../../chunks/chunk-MV4WHUIC.js";import"../../chunks/chunk-VKXEOL4K.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{isNativeBinaryInstall}from"../../chunks/chunk-NWGBDBZI.js";import"../../chunks/chunk-4SAVH3H7.js";import"../../chunks/chunk-ZS2WS4AM.js";import"../../chunks/chunk-AOWWC6WZ.js";import{directFetch}from"../../chunks/chunk-MY4MONOH.js";import{parseArguments}from"../../chunks/chunk-ELDHGU6N.js";import{buildCommandWithYes,outputActionRequired}from"../../chunks/chunk-BAT6SDBJ.js";import{getFlagsSpecification}from"../../chunks/chunk-MI7W4QMV.js";import{VERCEL_DIR,findRepoRoot,getLinkedProject,getVercelDirectory,require_lib,require_pluralize,resolveProjectCwd}from"../../chunks/chunk-U3NQZJQ4.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import{printAlignedLabel}from"../../chunks/chunk-IJCCFLCQ.js";import"../../chunks/chunk-ZQME5XUJ.js";import"../../chunks/chunk-2VBFQZ72.js";import{CantParseJSONFile,LambdaSizeExceededError,MissingDotenvVarsError,NowError,require_bytes}from"../../chunks/chunk-XSDAUM4F.js";import{cmd,getCommandName,getCommandNamePlain,getTitleName}from"../../chunks/chunk-JESNVRVR.js";import{Diagnostic,defineDiagnostics,init_dist,link_default,output_manager_default,require_build_utils}from"../../chunks/chunk-M774HRX5.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import{pkg_default}from"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import{require_supports_color}from"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__commonJS,__require,__toESM}from"../../chunks/chunk-BZENIQ7N.js";var require_bytes2=__commonJS({"../../node_modules/.pnpm/bytes@3.1.0/node_modules/bytes/index.js"(exports2,module2){"use strict";module2.exports=bytes2;module2.exports.format=format;module2.exports.parse=parse2;var formatThousandsRegExp=/\B(?=(\d{3})+(?!\d))/g,formatDecimalsRegExp=/(?:\.0*|(\.[^0]+)0+)$/,map={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},parseRegExp=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function bytes2(value,options){return typeof value=="string"?parse2(value):typeof value=="number"?format(value,options):null}function format(value,options){if(!Number.isFinite(value))return null;var mag=Math.abs(value),thousandsSeparator=options&&options.thousandsSeparator||"",unitSeparator=options&&options.unitSeparator||"",decimalPlaces=options&&options.decimalPlaces!==void 0?options.decimalPlaces:2,fixedDecimals=!!(options&&options.fixedDecimals),unit=options&&options.unit||"";(!unit||!map[unit.toLowerCase()])&&(mag>=map.pb?unit="PB":mag>=map.tb?unit="TB":mag>=map.gb?unit="GB":mag>=map.mb?unit="MB":mag>=map.kb?unit="KB":unit="B");var val=value/map[unit.toLowerCase()],str=val.toFixed(decimalPlaces);return fixedDecimals||(str=str.replace(formatDecimalsRegExp,"$1")),thousandsSeparator&&(str=str.replace(formatThousandsRegExp,thousandsSeparator)),str+unitSeparator+unit}function parse2(val){if(typeof val=="number"&&!isNaN(val))return val;if(typeof val!="string")return null;var results=parseRegExp.exec(val),floatValue,unit="b";return results?(floatValue=parseFloat(results[1]),unit=results[4].toLowerCase()):(floatValue=parseInt(val,10),unit="b"),Math.floor(map[unit]*floatValue)}}});var require_callsite_tostring=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/lib/compat/callsite-tostring.js"(exports2,module2){"use strict";module2.exports=callSiteToString2;function callSiteFileLocation(callSite){var fileName,fileLocation="";if(callSite.isNative()?fileLocation="native":callSite.isEval()?(fileName=callSite.getScriptNameOrSourceURL(),fileName||(fileLocation=callSite.getEvalOrigin())):fileName=callSite.getFileName(),fileName){fileLocation+=fileName;var lineNumber=callSite.getLineNumber();if(lineNumber!=null){fileLocation+=":"+lineNumber;var columnNumber=callSite.getColumnNumber();columnNumber&&(fileLocation+=":"+columnNumber)}}return fileLocation||"unknown source"}function callSiteToString2(callSite){var addSuffix=!0,fileLocation=callSiteFileLocation(callSite),functionName=callSite.getFunctionName(),isConstructor=callSite.isConstructor(),isMethodCall=!(callSite.isToplevel()||isConstructor),line="";if(isMethodCall){var methodName=callSite.getMethodName(),typeName=getConstructorName(callSite);functionName?(typeName&&functionName.indexOf(typeName)!==0&&(line+=typeName+"."),line+=functionName,methodName&&functionName.lastIndexOf("."+methodName)!==functionName.length-methodName.length-1&&(line+=" [as "+methodName+"]")):line+=typeName+"."+(methodName||"<anonymous>")}else isConstructor?line+="new "+(functionName||"<anonymous>"):functionName?line+=functionName:(addSuffix=!1,line+=fileLocation);return addSuffix&&(line+=" ("+fileLocation+")"),line}function getConstructorName(obj){var receiver=obj.receiver;return receiver.constructor&&receiver.constructor.name||null}}});var require_event_listener_count=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/lib/compat/event-listener-count.js"(exports2,module2){"use strict";module2.exports=eventListenerCount2;function eventListenerCount2(emitter,type){return emitter.listeners(type).length}}});var require_compat=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/lib/compat/index.js"(exports2,module2){"use strict";var EventEmitter=__require("events").EventEmitter;lazyProperty(module2.exports,"callSiteToString",function(){var limit=Error.stackTraceLimit,obj={},prep=Error.prepareStackTrace;function prepareObjectStackTrace2(obj2,stack3){return stack3}Error.prepareStackTrace=prepareObjectStackTrace2,Error.stackTraceLimit=2,Error.captureStackTrace(obj);var stack2=obj.stack.slice();return Error.prepareStackTrace=prep,Error.stackTraceLimit=limit,stack2[0].toString?toString:require_callsite_tostring()});lazyProperty(module2.exports,"eventListenerCount",function(){return EventEmitter.listenerCount||require_event_listener_count()});function lazyProperty(obj,prop,getter){function get(){var val=getter();return Object.defineProperty(obj,prop,{configurable:!0,enumerable:!0,value:val}),val}Object.defineProperty(obj,prop,{configurable:!0,enumerable:!0,get})}function toString(obj){return obj.toString()}}});var require_depd=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/index.js"(exports,module){var callSiteToString=require_compat().callSiteToString,eventListenerCount=require_compat().eventListenerCount,relative=__require("path").relative;module.exports=depd;var basePath=process.cwd();function containsNamespace(str,namespace){for(var vals=str.split(/[ ,]+/),ns=String(namespace).toLowerCase(),i=0;i<vals.length;i++){var val=vals[i];if(val&&(val==="*"||val.toLowerCase()===ns))return!0}return!1}function convertDataDescriptorToAccessor(obj,prop,message2){var descriptor=Object.getOwnPropertyDescriptor(obj,prop),value=descriptor.value;return descriptor.get=function(){return value},descriptor.writable&&(descriptor.set=function(val){return value=val}),delete descriptor.value,delete descriptor.writable,Object.defineProperty(obj,prop,descriptor),descriptor}function createArgumentsString(arity){for(var str="",i=0;i<arity;i++)str+=", arg"+i;return str.substr(2)}function createStackString(stack2){var str=this.name+": "+this.namespace;this.message&&(str+=" deprecated "+this.message);for(var i=0;i<stack2.length;i++)str+=`
8
8
  at `+callSiteToString(stack2[i]);return str}function depd(namespace){if(!namespace)throw new TypeError("argument namespace is required");var stack2=getStack(),site2=callSiteLocation(stack2[1]),file=site2[0];function deprecate2(message2){log.call(deprecate2,message2)}return deprecate2._file=file,deprecate2._ignored=isignored(namespace),deprecate2._namespace=namespace,deprecate2._traced=istraced(namespace),deprecate2._warned=Object.create(null),deprecate2.function=wrapfunction,deprecate2.property=wrapproperty,deprecate2}function isignored(namespace){if(process.noDeprecation)return!0;var str=process.env.NO_DEPRECATION||"";return containsNamespace(str,namespace)}function istraced(namespace){if(process.traceDeprecation)return!0;var str=process.env.TRACE_DEPRECATION||"";return containsNamespace(str,namespace)}function log(message2,site2){var haslisteners=eventListenerCount(process,"deprecation")!==0;if(!(!haslisteners&&this._ignored)){var caller,callFile,callSite,depSite,i=0,seen=!1,stack2=getStack(),file=this._file;for(site2?(depSite=site2,callSite=callSiteLocation(stack2[1]),callSite.name=depSite.name,file=callSite[0]):(i=2,depSite=callSiteLocation(stack2[i]),callSite=depSite);i<stack2.length;i++)if(caller=callSiteLocation(stack2[i]),callFile=caller[0],callFile===file)seen=!0;else if(callFile===this._file)file=this._file;else if(seen)break;var key=caller?depSite.join(":")+"__"+caller.join(":"):void 0;if(!(key!==void 0&&key in this._warned)){this._warned[key]=!0;var msg=message2;if(msg||(msg=callSite===depSite||!callSite.name?defaultMessage(depSite):defaultMessage(callSite)),haslisteners){var err=DeprecationError(this._namespace,msg,stack2.slice(i));process.emit("deprecation",err);return}var format=process.stderr.isTTY?formatColor:formatPlain,output=format.call(this,msg,caller,stack2.slice(i));process.stderr.write(output+`
9
9
  `,"utf8")}}}function callSiteLocation(callSite){var file=callSite.getFileName()||"<anonymous>",line=callSite.getLineNumber(),colm=callSite.getColumnNumber();callSite.isEval()&&(file=callSite.getEvalOrigin()+", "+file);var site2=[file,line,colm];return site2.callSite=callSite,site2.name=callSite.getFunctionName(),site2}function defaultMessage(site2){var callSite=site2.callSite,funcName=site2.name;funcName||(funcName="<anonymous@"+formatLocation(site2)+">");var context=callSite.getThis(),typeName=context&&callSite.getTypeName();return typeName==="Object"&&(typeName=void 0),typeName==="Function"&&(typeName=context.name||typeName),typeName&&callSite.getMethodName()?typeName+"."+funcName:funcName}function formatPlain(msg,caller,stack2){var timestamp=new Date().toUTCString(),formatted=timestamp+" "+this._namespace+" deprecated "+msg;if(this._traced){for(var i=0;i<stack2.length;i++)formatted+=`
10
10
  at `+callSiteToString(stack2[i]);return formatted}return caller&&(formatted+=" at "+formatLocation(caller)),formatted}function formatColor(msg,caller,stack2){var formatted="\x1B[36;1m"+this._namespace+"\x1B[22;39m \x1B[33;1mdeprecated\x1B[22;39m \x1B[0m"+msg+"\x1B[39m";if(this._traced){for(var i=0;i<stack2.length;i++)formatted+=`
@@ -52,7 +52,7 @@ ${partHeaders}\r
52
52
  `)))}parts.push(Uint8Array.from(Buffer.from(`--${boundary}--\r
53
53
  `)));let body=Buffer.concat(parts);res.writeHead(200,{"Content-Type":`multipart/mixed; boundary=${boundary}`,"Content-Length":body.length}),res.end(body);return}let leaseMatch=topicPath.match(/^([A-Za-z0-9_-]+)\/consumer\/([A-Za-z0-9_-]+)\/lease\/([^/]+)(?:\/visibility)?$/);if(leaseMatch&&(req.method==="DELETE"||req.method==="PATCH")){let[,,consumer,receiptHandle]=leaseMatch,messageId=this.queueBroker.findMessageIdByReceiptHandle(consumer,receiptHandle);if(!messageId){res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Message not found"}));return}if(req.method==="DELETE"){this.queueBroker.acknowledge(messageId,consumer,receiptHandle),res.writeHead(204),res.end();return}let body=await(0,import_raw_body2.default)(req),timeoutSeconds=DEV_QUEUES_DEFAULT_VISIBILITY_TIMEOUT_SECONDS;try{let parsed=JSON.parse(body.toString());typeof parsed.visibilityTimeoutSeconds=="number"&&parsed.visibilityTimeoutSeconds>=0&&(timeoutSeconds=parsed.visibilityTimeoutSeconds)}catch(err){output_manager_default.debug(`queues: failed to parse visibility timeout body: ${err}`)}this.queueBroker.changeVisibility(messageId,consumer,receiptHandle,timeoutSeconds),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}res.writeHead(404),res.end("Not Found")};this.handleRuntimeCacheRoute=async(req,res,pathname)=>{let store=this.runtimeCache;if(!store){res.writeHead(503),res.end("Runtime Cache not initialized");return}if(!pathname.startsWith(DEV_RUNTIME_CACHE_API_PREFIX)){res.writeHead(404),res.end("Not Found");return}let itemPath=pathname.slice(DEV_RUNTIME_CACHE_API_PREFIX.length),searchParams=new URL2(req.url||"/","http://localhost").searchParams;if(itemPath==="revalidate"){if(req.method!=="POST"){res.writeHead(405),res.end("Method Not Allowed");return}let tags=(searchParams.get("tags")||"").split(",").map(tag=>tag.trim()).filter(Boolean),itemId=searchParams.get("itemId")||void 0;if(tags.length===0&&!itemId){res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"No tags or itemId provided"}));return}tags.length>0&&(store.expireTags(tags),output_manager_default.debug(`runtime cache: expired tags "${tags.join(",")}"`)),itemId&&(store.delete(itemId),output_manager_default.debug(`runtime cache: expired item "${itemId}"`)),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({revalidated:!0}));return}let key;try{key=decodeURIComponent(itemPath)}catch{res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid cache key"}));return}if(!key){res.writeHead(404),res.end("Not Found");return}if(req.method==="GET"){let hit=store.get(key);if(!hit){output_manager_default.debug(`runtime cache: MISS "${key}"`),res.writeHead(404),res.end("Not Found");return}output_manager_default.debug(`runtime cache: HIT "${key}"`);let headers={"Content-Type":"application/json","Content-Length":hit.value.length,[HEADER_CACHE_STATE]:"fresh",Age:String(hit.ageSeconds)};hit.tags.length>0&&(headers[HEADER_CACHE_TAGS]=hit.tags.join(",")),res.writeHead(200,headers),res.end(hit.value);return}if(req.method==="POST"){let revalidateHeader=req.headers[HEADER_REVALIDATE],ttlSeconds;if(revalidateHeader)if(revalidateHeader==="Infinity"||["false","False","FALSE","f","F"].includes(revalidateHeader))ttlSeconds=DEV_RUNTIME_CACHE_ONE_YEAR_SECONDS;else if(/^[+-]?\d+$/.test(revalidateHeader)){let parsedRevalidate=Number(revalidateHeader);if(!Number.isSafeInteger(parsedRevalidate)||parsedRevalidate<0){res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid revalidate value"}));return}if(parsedRevalidate===0){res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}ttlSeconds=parsedRevalidate}else{res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid revalidate value"}));return}let value;try{value=await(0,import_raw_body2.default)(req,{limit:DEV_RUNTIME_CACHE_MAX_ITEM_SIZE})}catch(err){if(err.statusCode===413){res.writeHead(413,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Cache item is too large"}));return}throw err}let tagsHeader=req.headers[HEADER_CACHE_TAGS];store.set(key,value,{ttlSeconds,tags:(tagsHeader||"").split(",").map(tag=>tag.trim()).filter(Boolean)});let name=req.headers[HEADER_CACHE_ITEM_NAME];output_manager_default.debug(`runtime cache: SET "${key}"${name?` (${name})`:""} ${value.length} bytes`),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}if(req.method==="DELETE"){store.delete(key),output_manager_default.debug(`runtime cache: DELETE "${key}"`),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}res.writeHead(405),res.end("Method Not Allowed")};this.serveProjectAsNowV2=async(req,res,requestId,vercelConfig,routes=vercelConfig.routes,callLevel=0)=>{let{debug}=output_manager_default;if(callLevel===0&&await this.handleSchedulesProxyRequest(req,res))return;let parsed=url3.parse(req.url||"/");if(typeof parsed.pathname=="string"&&parsed.pathname.includes("//")){let location=parsed.pathname.replace(/\/+/g,"/");if(parsed.search&&(location+=parsed.search),req.method==="GET"){await this.sendRedirect(req,res,requestId,location,301);return}debug(`Rewriting URL from "${req.url}" to "${location}"`),req.url=location}let queueProxyPrefix=`${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`,runtimeCacheProxyPrefix=`${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}`;if(callLevel===0&&this.queueBroker){let pathname=parsed.pathname||"/";if(pathname.startsWith(`${queueProxyPrefix}/`)){if(!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}await this.handleQueuesRoute(req,res,pathname.slice(queueProxyPrefix.length));return}}if(callLevel===0){let pathname=parsed.pathname||"/";if(pathname.startsWith(`${runtimeCacheProxyPrefix}/`)){if(!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}await this.handleRuntimeCacheRoute(req,res,pathname.slice(runtimeCacheProxyPrefix.length));return}}if(callLevel===0&&this.bulkRedirects){let bulkMatch=resolveBulkRedirect(this.bulkRedirects,req.url||"/",typeof req.headers.host=="string"?req.headers.host:void 0);if(bulkMatch){debug(`Bulk redirect ${bulkMatch.statusCode}: ${req.url} -> ${bulkMatch.location}`),await this.sendRedirect(req,res,requestId,bulkMatch.location,bulkMatch.statusCode);return}}if(callLevel===0&&this.orchestrator){let pathname=parsed.pathname||"/",service=this.orchestrator.getServiceForRoute(pathname);if(service){debug(`Found service: ${service.name}`);let upstream=`http://${service.host}:${service.port}`;debug(`Proxying to service "${service.name}": ${upstream}`);let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.setResponseHeaders(res,requestId),proxyPass(req,res,upstream,this,requestId,!1)}}callLevel===0&&await this.updateBuildMatches(vercelConfig),this.blockingBuildsPromise&&(debug("Waiting for builds to complete before handling request"),await this.blockingBuildsPromise);let getReqUrl=rr=>{if(rr.dest){if(rr.query){let destParsed=url3.parse(rr.dest),destQuery=parseQueryString(destParsed.search);return Object.assign(destQuery,rr.query),destParsed.search=formatQueryString(destQuery),url3.format(destParsed)}return rr.dest}return req.url},handleMap=getRoutesTypes(routes),missRoutes=handleMap.get("miss")||[],hitRoutes=handleMap.get("hit")||[],errorRoutes=handleMap.get("error")||[],filesystemRoutes=handleMap.get("filesystem")||[],phases=[null,"filesystem"],routeResult=null,match=null,statusCode,prevUrl=req.url,prevHeaders={},requestTransforms=[],responseTransforms,middlewares=[...this.buildMatches.values()].filter(m=>m.config?.middleware===!0);for(let middleware of middlewares){let startMiddlewareResult,middlewarePid,{envConfigs,files,devCacheDir,cwd:workPath}=this;try{let{builder:builder2}=middleware.builderWithPkg;if(typeof builder2.startDevServer=="function"&&(startMiddlewareResult=await builder2.startDevServer({files,entrypoint:middleware.entrypoint,workPath,repoRootPath:this.repoRoot,config:{projectSettings:this.projectSettings,...middleware.config},meta:{isDev:!0,...this.getDevResourceMeta(),devCacheDir,requestUrl:req.url,env:this.getBuilderDevEnv(middleware,envConfigs.runEnv),buildEnv:{...envConfigs.buildEnv}}})),startMiddlewareResult){let{port,pid,shutdown}=startMiddlewareResult;middlewarePid=pid,this.shutdownCallbacks.set(pid,shutdown),debug(`Invoking middleware "${middleware.src}" (port=${port})`);let middlewareReqHeaders=nodeHeadersToFetchHeaders(req.headers),proxyHeaders=this.getProxyHeaders(req,requestId,!0);for(let[name,value]of nodeHeadersToFetchHeaders(proxyHeaders))middlewareReqHeaders.set(name,value);let middlewareReqPath=url3.parse(req.url||"/").path||"/",middlewareRes=await directFetch(`http://127.0.0.1:${port}${middlewareReqPath}`,{headers:middlewareReqHeaders,method:req.method,redirect:"manual"}),middlewareBody=Buffer.from(await middlewareRes.arrayBuffer());if(middlewareRes.status===500&&middlewareBody.byteLength===0){await this.sendError(req,res,requestId,"EDGE_FUNCTION_INVOCATION_FAILED",500);return}res.statusCode=middlewareRes.status;let rewritePath="",contentType2="",shouldContinue=!1,skipMiddlewareHeaders=new Set(["date","connection","content-length","transfer-encoding"]),middlewareHeaders=applyOverriddenHeaders(req.headers,middlewareRes.headers);for(let[name,value]of middlewareHeaders)name==="x-middleware-next"?shouldContinue=value==="1":name==="x-middleware-rewrite"?(rewritePath=value,shouldContinue=!0):name==="content-type"?contentType2=value:skipMiddlewareHeaders.has(name)||(applyChainResponseHeader(res,name,value),req.headers[name]=value);if(!shouldContinue){this.setResponseHeaders(res,requestId),middlewareBody.length>0?(res.setHeader("content-length",middlewareBody.length),contentType2&&res.setHeader("content-type",contentType2),res.end(middlewareBody)):res.end();return}if(rewritePath){debug(`Detected rewrite path from middleware: "${rewritePath}"`),prevUrl=rewritePath;let beforeRewriteUrl=req.url||"/";if(isURL(rewritePath)){let rewriteUrlParsed=new URL2(rewritePath);if(this.address.origin===rewriteUrlParsed.origin)req.url=rewritePath.slice(rewriteUrlParsed.origin.length)||"/",prevUrl=req.url;else{debug(`ProxyPass: ${rewritePath}`),this.setResponseHeaders(res,requestId),proxyPass(req,res,rewritePath,this,requestId);return}}else{let rewriteUrlParsed=url3.parse(beforeRewriteUrl);rewriteUrlParsed.search=url3.parse(rewritePath).search,req.url=url3.format(rewriteUrlParsed)}debug(`Rewrote incoming HTTP URL from "${beforeRewriteUrl}" to "${req.url}"`)}}}catch(err){(0,import_error_utils.isSpawnError)(err)&&err.code==="ENOENT"&&(err.message=`Command not found: ${import_chalk2.default.cyan(err.path,...err.spawnargs)}
54
54
  Please ensure that ${cmd(err.path)} is properly installed`,err.link="https://vercel.link/command-not-found"),output_manager_default.prettyError(err),await this.sendError(req,res,requestId,"MIDDLEWARE_INVOCATION_FAILED",500);return}finally{middlewarePid&&this.killBuilderDevServer(middlewarePid)}}for(let phase of phases){statusCode=void 0;let phaseRoutes=handleMap.get(phase)||[];if(routeResult=await devRouter(prevUrl,req.method,phaseRoutes,this,vercelConfig,prevHeaders,missRoutes,phase),routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms),routeResult.continue&&(routeResult.dest&&(prevUrl=getReqUrl(routeResult)),routeResult.headers&&(prevHeaders=routeResult.headers)),callLevel===0&&this.orchestrator&&!routeResult.continue&&isServiceDestination(routeResult.matched_route))return this.delegateToService(req,res,requestId,routeResult.matched_route,vercelConfig,requestTransforms,responseTransforms);if(routeResult.isDestUrl){let destParsed=url3.parse(routeResult.dest),destQuery=parseQueryString(destParsed.search);Object.assign(destQuery,routeResult.query),destParsed.search=formatQueryString(destQuery);let destUrl=url3.format(destParsed);return this.prepareTransforms(req,requestTransforms,responseTransforms),debug(`ProxyPass: ${destUrl}`),this.setResponseHeaders(res,requestId),proxyPass(req,res,destUrl,this,requestId)}if(match=await findBuildMatch(this.buildMatches,this.files,routeResult.dest,this,vercelConfig),await this.exitWithStatus(match,routeResult,phase,req,res,requestId,responseTransforms))return;if(!match&&missRoutes.length>0){if(routeResult=await devRouter(getReqUrl(routeResult),req.method,missRoutes,this,vercelConfig,routeResult.headers,[],"miss"),routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms),match=await findBuildMatch(this.buildMatches,this.files,routeResult.dest,this,vercelConfig),await this.exitWithStatus(match,routeResult,phase,req,res,requestId,responseTransforms))return}else if(match&&hitRoutes.length>0){let prevStatus=routeResult.status;routeResult=await devRouter(getReqUrl(routeResult),req.method,hitRoutes,this,vercelConfig,routeResult.headers,[],"hit"),routeResult.status=prevStatus,routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms)}if(statusCode=routeResult.status,match||phase===null&&filesystemRoutes.length===0)break}if(!match&&routeResult&&errorRoutes.length>0){let routeResultForError=await devRouter(getReqUrl(routeResult),req.method,errorRoutes,this,vercelConfig,routeResult.headers,[],"error"),{matched_route}=routeResultForError,matchForError=await findBuildMatch(this.buildMatches,this.files,routeResultForError.dest,this,vercelConfig);if(matchForError)debug("Route match detected in error phase, breaking loop"),routeResult=routeResultForError,statusCode=routeResultForError.status,match=matchForError,routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms);else if(matched_route&&matched_route.src&&!matched_route.dest&&(debug("Route without `dest` detected in error phase, attempting to exit early"),await this.exitWithStatus(matchForError,routeResultForError,"error",req,res,requestId,responseTransforms)))return}if(!routeResult)throw dev.DEV_INTERNAL_NO_ROUTE_RESULT();let{dest,query,headers}=routeResult;for(let[name,value]of Object.entries(headers))res.setHeader(name,value);statusCode&&Object.defineProperty(res,"statusCode",{get(){return statusCode},set(_){}});let requestPath=dest.replace(/^\//,"");if(!match){if(this.devProcessOrigin){let upstream=this.devProcessOrigin;debug(`Proxying to frontend dev server: ${upstream}`);let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;this.setResponseHeaders(res,requestId);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);return origUrl.pathname=dest,Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format(origUrl),this.prepareTransforms(req,requestTransforms,responseTransforms),proxyPass(req,res,upstream,this,requestId,!1)}(statusCode===404&&routeResult.phase==="miss"||!this.renderDirectoryListing(req,res,requestPath,requestId))&&await this.send404(req,res,requestId);return}let buildRequestPath=match.buildResults.has(null)?null:requestPath,buildResult=match.buildResults.get(buildRequestPath);if(buildResult&&Array.isArray(buildResult.routes)&&buildResult.routes.length>0){let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);origUrl.pathname=dest,Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery);let newUrl=url3.format(origUrl);debug(`Checking build result's ${buildResult.routes.length} \`routes\` to match ${newUrl}`);let matchedRoute=await devRouter(newUrl,req.method,buildResult.routes,this,vercelConfig);if(matchedRoute.found&&callLevel===0){debug(`Found matching route ${matchedRoute.dest} for ${newUrl}`),req.url=newUrl,await this.serveProjectAsNowV2(req,res,requestId,vercelConfig,buildResult.routes,callLevel+1);return}}let{builder,pkg:builderPkg}=match.builderWithPkg;if(typeof builder.startDevServer=="function"){let devServerResult=null;try{devServerResult=await this.startBuildMatchDevServer(match,requestPath)}catch(err){(0,import_error_utils.isSpawnError)(err)&&err.code==="ENOENT"&&(err.message=`Command not found: ${import_chalk2.default.cyan(err.path,...err.spawnargs)}
55
- Please ensure that ${cmd(err.path)} is properly installed`,err.link="https://vercel.link/command-not-found"),output_manager_default.prettyError(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}if(devServerResult){requestId=generateRequestId(this.podId,!0);let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown),persistent||res.once("close",()=>{this.killBuilderDevServer(pid)}),debug(`Proxying to "${builderPkg.name}" dev server (port=${port}, pid=${pid})`);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search});let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,`http://127.0.0.1:${port}`,this,requestId,!1)}else debug(`Skipping \`startDevServer()\` for ${match.entrypoint}`)}let foundAsset=findAsset(match,requestPath,vercelConfig);if(!foundAsset&&callLevel===0&&(await this.triggerBuild(match,buildRequestPath,req,vercelConfig),foundAsset=findAsset(match,requestPath,vercelConfig)),this.devProcessOrigin&&(!foundAsset||foundAsset&&foundAsset.asset.type!=="Lambda")){debug("Proxying to frontend dev server");let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,this.devProcessOrigin,this,requestId,!1)}if(!foundAsset){await this.send404(req,res,requestId);return}let{asset,assetKey}=foundAsset;switch(debug(`Serving asset: [${asset.type}] ${assetKey} ${asset.contentType||""}`),asset.type){case"FileFsRef":this.setResponseHeaders(res,requestId);let staticResHeaders={};applyResponseTransforms(staticResHeaders,responseTransforms??[]);for(let[name,value]of Object.entries(staticResHeaders))value!==void 0&&res.setHeader(name,value);return req.url=`/${basename(asset.fsPath)}`,serveStaticFile(req,res,dirname3(asset.fsPath),{headers:[{source:"**/*",headers:[{key:"Content-Type",value:asset.contentType||getMimeType(assetKey)}]}]});case"FileBlob":let headers2={"Content-Length":asset.data.length,"Content-Type":asset.contentType||getMimeType(assetKey)};applyResponseTransforms(headers2,responseTransforms??[]),this.setResponseHeaders(res,requestId,headers2),res.end(asset.data);return;case"Lambda":if(!asset.fn){await this.sendError(req,res,requestId,"INTERNAL_LAMBDA_NOT_FOUND");return}requestId=generateRequestId(this.podId,!0);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search}),applyRequestTransforms(req,requestTransforms);let path6=req.url||"/",body=await(0,import_raw_body2.default)(req);debug(`Invoking lambda: "${assetKey}" with ${path6}`);let result;try{result=await this.invokeBuiltLambda(asset,req,requestId,body)}catch(err){console.error(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}statusCode||(res.statusCode=result.statusCode);let lambdaHeaders=result.headers??{};applyResponseTransforms(lambdaHeaders,responseTransforms??[]),this.setResponseHeaders(res,requestId,lambdaHeaders);let resBody;return result.encoding==="base64"&&typeof result.body=="string"?resBody=Buffer.from(result.body,"base64"):resBody=result.body,res.end(resBody);default:await this.sendError(req,res,requestId,"UNKNOWN_ASSET_TYPE")}};if(this.cwd=cwd,this.repoRoot=options.repoRoot??cwd,this.envConfigs={buildEnv:{},runEnv:{},allEnv:{}},this.envValues=options.envValues||{},this.projectId=options.projectId,this.orgId=options.orgId,this.queuePort=options.queuePort,this.runtimeCachePort=options.runtimeCachePort,this.schedulesPort=options.schedulesPort,this.routing=options.routing??!0,this.devCommandPort=options.devCommandPort,!this.routing&&!this.devCommandPort)throw new Error("Running without the router needs a `devCommandPort`");this.scheduleBroker=new import_local_schedules2.ScheduleBroker({ownerId:this.orgId??"team_local",projectId:this.projectId??"prj_local",trackId:"development",dispatch:invocation=>this.dispatchSchedule(invocation),onError:(err,invocation)=>{try{output_manager_default.error(`Failed to dispatch schedule "${invocation.schedule.name}": ${(0,import_error_utils.errorToString)(err)}`)}catch{}}}),this.resourceProxyToken=randomBytes2(32).toString("base64url"),this.reportError=createErrorReporter2(code=>options.onErrorCode?.(code)),this.files={},this.originalProjectSettings=options.projectSettings,this.projectSettings=options.projectSettings,this.services=options.services,this.useImplicitServicesEnvInjection=options.useImplicitServicesEnvInjection??!0,this.caseSensitive=!1,this.apiDir=null,this.apiExtensions=new Set,this.proxy=import_http_proxy_node16.default.createProxyServer({changeOrigin:!0,ws:!0,xfwd:!0}),this.proxy.on("proxyRes",(proxyRes,req)=>{proxyRes.headers.server="Vercel";let responseTransforms=this.responseTransformsByReq.get(req);responseTransforms&&(this.responseTransformsByReq.delete(req),applyResponseTransforms(proxyRes.headers,responseTransforms))}),this.proxy.on("error",(err,req,res)=>{if(output_manager_default.debug(`Proxy error for ${req?.url??"unknown request"}: ${(0,import_error_utils.errorToString)(err)}`),!!res){if("destroy"in res&&typeof res.destroy=="function"){res.destroy();return}res instanceof http.ServerResponse&&(res.headersSent||res.writeHead(502),res.end())}}),this.server=http.createServer(this.devServerHandler),this.server.timeout=0,this.queueServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.queueOrigin,this.handleQueuesRoute)}),this.runtimeCacheServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.runtimeCacheOrigin,this.handleRuntimeCacheRoute)}),this.schedulesServer=http.createServer((req,res)=>{this.schedulesSession&&res.setHeader(LOCAL_SCHEDULES_SESSION_HEADER,this.schedulesSession.session.id),this.handleResourceServerRequest(req,res,this.schedulesOrigin,this.handleSchedulesRoute)}),this.stopping=!1,this.buildMatches=new Map,this.inProgressBuilds=new Map,this.devCacheDir=join4(getVercelDirectory(cwd),"cache"),this.vercelConfigWarning=!1,this.getVercelConfigPromise=null,this.blockingBuildsPromise=null,this.startPromise=null,this.bulkRedirects=null,this.bulkRedirectsSignature=null,this.bulkRedirectsLastPath=null,this.bulkRedirectsResolvedPath=null,this.bulkRedirectsDirty=!0,this.watchAggregationId=null,this.watchAggregationEvents=[],this.watchAggregationTimeout=500,this.filter=path6=>!!path6,this.podId=Math.random().toString(32).slice(-5),this.shutdownCallbacks=new Map}get address(){if(!this._address)throw dev.DEV_INTERNAL_ADDRESS_UNAVAILABLE();return this._address}shouldUseServicesOrchestrator(){return!!(this.services&&this.services.length>0)}hasSubscribers(){return!!this.sidecars?.length}getDevQueueEnv(){return this.queueOrigin?getDevQueueEnv(this.queueOrigin,this.hasSubscribers()):{}}getDevRuntimeCacheEnv(env){return!this.runtimeCacheOrigin||env.RUNTIME_CACHE_ENDPOINT?{}:process.env.RUNTIME_CACHE_ENDPOINT?{RUNTIME_CACHE_ENDPOINT:process.env.RUNTIME_CACHE_ENDPOINT,...process.env.RUNTIME_CACHE_HEADERS?{RUNTIME_CACHE_HEADERS:process.env.RUNTIME_CACHE_HEADERS}:{}}:getDevRuntimeCacheEnv(this.runtimeCacheOrigin,DEV_RUNTIME_CACHE_API_PREFIX)}get resourceEndpoints(){if(!this.queueOrigin||!this.runtimeCacheOrigin)throw new Error("Local resource servers have not started");let proxied=(direct,path6)=>this.routing?`${this.address.origin}${path6}`:direct,runtimeCache=`${this.runtimeCacheOrigin}${DEV_RUNTIME_CACHE_API_PREFIX}`;return{queues:{direct:this.queueOrigin,proxy:proxied(this.queueOrigin,`${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`)},runtimeCache:{direct:runtimeCache,proxy:proxied(runtimeCache,`${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}${DEV_RUNTIME_CACHE_API_PREFIX}`)},...this.schedulesOrigin?{schedules:{direct:this.schedulesOrigin,proxy:proxied(this.schedulesOrigin,`${DEV_SCHEDULES_PROXY_PREFIX}/${this.resourceProxyToken}`)}}:{}}}getDevResourceMeta(){return{devResourceEndpoints:this.resourceEndpoints}}handleResourceServerRequest(req,res,origin,handler){if(!origin||!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}if(!isValidDevResourceHost(origin,req.headers.host)){res.writeHead(403),res.end("Forbidden");return}let pathname=new URL2(req.url||"/","http://127.0.0.1").pathname;handler(req,res,pathname).catch(err=>{output_manager_default.debug(`Local resource request failed for ${req.url||"/"}: ${(0,import_error_utils.errorToString)(err)}`),res.headersSent||res.writeHead(500),res.end("Internal Server Error")})}isAuthorizedResourceRequest(req,token){let authorization=req.headers.authorization;if(typeof authorization!="string")return!1;let encoder=new TextEncoder,actual=encoder.encode(authorization),expected=encoder.encode(`Bearer ${token}`);return actual.length===expected.length&&timingSafeEqual(actual,expected)}getBuilderDevEnv(match,env){let result={...env,...getDevSchedulesEnv(this.schedulesOrigin)};if(match.builderWithPkg.pkg.name!=="@vercel/container")return result;let endpoints=this.resourceEndpoints;return Object.assign(result,getDevSchedulesEnv(endpoints.schedules?.proxy,!0)),result.VERCEL_QUEUE_BASE_URL===endpoints.queues.direct&&Object.assign(result,getDevQueueEnv(endpoints.queues.proxy,result.VERCEL_HAS_WORKER_SERVICES!==void 0)),result.RUNTIME_CACHE_ENDPOINT===endpoints.runtimeCache.direct&&Object.assign(result,getDevRuntimeCacheEnv(endpoints.runtimeCache.proxy,"")),result}getSidecarDevMeta(match){let serviceCount=(this.sidecars??[]).filter(sidecar=>sidecar.builder.use!==match.use?!1:!sidecar.workspace||sidecar.workspace===".").length;return serviceCount>0?{serviceCount}:{}}async setupBuilderDevSidecars(){if(this.shouldUseServicesOrchestrator())return;let sidecars=this.sidecars??[];if(sidecars.length===0)return;Object.assign(this.envConfigs.runEnv,this.getDevQueueEnv());let services=sidecars.map(toOrchestratorService),orchestrator=new ServicesOrchestrator({services,cwd:this.cwd,repoRoot:this.repoRoot,env:this.envConfigs.allEnv,proxyOrigin:this.address.origin,resourceEndpoints:this.resourceEndpoints,useImplicitEnvInjection:!1,preferServiceBuilder:!0,onQueueSubscriptions:(serviceName,subscriptions)=>this.queueBroker?.updateServiceSubscriptions(serviceName,subscriptions)});this.sidecarOrchestrator=orchestrator,this.queueBroker?.registerServices(services);try{await orchestrator.startAll()}catch(err){throw await orchestrator.stopAll(),this.sidecarOrchestrator=void 0,this.sidecars=[],err}output_manager_default.log(`Started ${sidecars.length} development ${(0,import_pluralize2.default)("sidecar",sidecars.length)}`)}async exit(code=1){await this.stop(code),process.exit(code)}enqueueFsEvent(type,path6){this.bulkRedirectsResolvedPath&&(path6===this.bulkRedirectsResolvedPath||path6.startsWith(this.bulkRedirectsResolvedPath+sep2))&&(this.bulkRedirectsDirty=!0),this.watchAggregationEvents.push({type,path:path6}),this.watchAggregationId===null&&(this.watchAggregationId=setTimeout(()=>{let events=this.watchAggregationEvents.slice();this.watchAggregationEvents.length=0,this.watchAggregationId=null,this.handleFilesystemEvents(events).catch(err=>{output_manager_default.prettyError(err),(0,import_error_utils.isError)(err)&&typeof err.stack=="string"&&output_manager_default.debug(err.stack)})},this.watchAggregationTimeout))}async handleFilesystemEvents(events){if(this.stopping)return;output_manager_default.debug(`Filesystem watcher notified of ${events.length} events`);let filesChanged=new Set,filesRemoved=new Set,distPaths=[];for(let buildMatch of this.buildMatches.values())for(let buildResult of buildMatch.buildResults.values())buildResult.distPath&&distPaths.push(buildResult.distPath);if(events=events.filter(event=>distPaths.every(distPath=>!event.path.startsWith(distPath))),events.length!==0){this.functionReconciliations++;try{this.configGeneration++,this.functionDiscovery=void 0;for(let event of events)event.type==="add"?await this.handleFileCreated(event.path,filesChanged,filesRemoved):event.type==="unlink"?this.handleFileDeleted(event.path,filesChanged,filesRemoved):event.type==="change"&&await this.handleFileModified(event.path,filesChanged,filesRemoved);let vercelConfig=await this.getVercelConfig();if(this.stopping)return;await this.updateBuildMatches(vercelConfig);let filesChangedArray=[...filesChanged],filesRemovedArray=[...filesRemoved],needsRebuild=new Map;for(let match of this.buildMatches.values()){this.canonicalizeFunctionBuild(match);for(let[requestPath,result]of match.buildResults)if(!needsRebuild.has(result)&&Array.isArray(result.watch)){for(let pattern of result.watch)if(minimatches(filesChangedArray,pattern)||minimatches(filesRemovedArray,pattern)){needsRebuild.set(result,[requestPath,match]);break}}}if(needsRebuild.size>0){output_manager_default.debug(`Triggering ${needsRebuild.size} rebuilds`),filesChangedArray.length>0&&output_manager_default.debug(`Files changed: ${filesChangedArray.join(", ")}`),filesRemovedArray.length>0&&output_manager_default.debug(`Files removed: ${filesRemovedArray.join(", ")}`);for(let[result,[requestPath,match]]of needsRebuild)requestPath===null||await shouldServe(match,this.files,requestPath,this,vercelConfig)?this.triggerBuild(match,requestPath,null,vercelConfig,result,filesChangedArray,filesRemovedArray).catch(err=>{output_manager_default.warn(`An error occurred while rebuilding \`${match.src}\`:`),console.error(err.stack)}):output_manager_default.debug(`Not rebuilding because \`shouldServe()\` returned \`false\` for "${match.use}" request path "${requestPath}"`)}}finally{this.functionReconciliations--}}}async handleFileCreated(fsPath,changed,removed){let name=relative2(this.cwd,fsPath);try{await this.getVercelConfig(),this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath});let extensionless=this.getExtensionlessFile(name);extensionless&&(this.files[extensionless]=await import_build_utils9.FileFsRef.fromFsPath({fsPath})),fileChanged(name,changed,removed),output_manager_default.debug(`File created: ${name}`)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File created, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}handleFileDeleted(fsPath,changed,removed){let name=relative2(this.cwd,fsPath);output_manager_default.debug(`File deleted: ${name}`),fileRemoved(name,this.files,changed,removed);let extensionless=this.getExtensionlessFile(name);extensionless&&(output_manager_default.debug(`File deleted: ${extensionless}`),fileRemoved(extensionless,this.files,changed,removed))}async handleFileModified(fsPath,changed,removed){let name=relative2(this.cwd,fsPath);try{this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath}),fileChanged(name,changed,removed),output_manager_default.debug(`File modified: ${name}`)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File modified, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}async updateBuildMatches(vercelConfig,isInitial=!1){let fileList=this.resolveBuildFiles(this.files),matches=await getBuildMatches(vercelConfig,this.cwd,this,fileList),sources=matches.map(m=>m.src);isInitial&&fileList.length===0&&output_manager_default.warn("There are no files inside your deployment.");let ops=[];for(let src of this.buildMatches.keys())if(!sources.includes(src)){output_manager_default.debug(`Removing build match for "${src}"`);let match=this.buildMatches.get(src);match&&ops.push(shutdownBuilder(match)),this.buildMatches.delete(src)}await Promise.all(ops);let blockingBuilds=[];for(let match of matches){let currentMatch=this.buildMatches.get(match.src);if(!buildMatchEquals(currentMatch,match)&&(output_manager_default.debug(`Adding build match for "${match.src}" with "${match.use}"`),this.buildMatches.set(match.src,match),!isInitial&&needsBlockingBuild(match))){let buildPromise=executeBuild(vercelConfig,this,this.files,match,null,!1);blockingBuilds.push(buildPromise)}}blockingBuilds.length>0&&(output_manager_default.debug(`Waiting for ${blockingBuilds.length} "blocking builds"`),this.blockingBuildsPromise=Promise.all(blockingBuilds).then(()=>{output_manager_default.debug('Cleaning up "blockingBuildsPromise" after successful resolve'),this.blockingBuildsPromise=null}).catch(err=>{output_manager_default.debug(`Cleaning up "blockingBuildsPromise" after error: ${err}`),this.blockingBuildsPromise=null,err&&output_manager_default.prettyError(err)})),this.buildMatches=new Map([...this.buildMatches.entries()].sort((matchA,matchB)=>sortBuilders(matchA[1],matchB[1])))}async getLocalEnv(fileName,base){let filePath=join4(this.cwd,fileName),env={};try{let dotenv=await import_fs_extra.default.readFile(filePath,"utf8");output_manager_default.debug(`Using local env: ${filePath}`),env=(0,import_dotenv.parse)(dotenv),env=this.injectSystemValuesInDotenv(env)}catch(err){if(!(0,import_error_utils.isErrnoException)(err)||err.code!=="ENOENT")throw err}try{return{...this.validateEnvConfig(fileName,base||{},env)}}catch(err){if(err instanceof MissingDotenvVarsError)this.reportError(err),await this.exit();else throw err}return{}}getVercelConfig(){if(this.getVercelConfigPromise)return this.getVercelConfigPromise;this.getVercelConfigPromise=(async()=>{for(;;){let generation=this.configGeneration;try{let config=await this._getVercelConfig();if(this.stopping||generation===this.configGeneration)return config}catch(err){if(this.stopping||generation===this.configGeneration)throw err}this.functionDiscovery=void 0}})();let clear=this.clearVercelConfigPromise;return this.getVercelConfigPromise.then(clear,clear),this.getVercelConfigPromise}get devCommand(){return this.getDevCommand(this.projectSettings)}get devCommandOrigin(){return this.devProcessOrigin}getDevCommand(projectSettings){if(projectSettings?.devCommand)return projectSettings.devCommand;if(projectSettings?.framework){let frameworkSlug=projectSettings.framework,framework=import_frameworks3.frameworkList.find(f=>f.slug===frameworkSlug);if(framework){let defaults=framework.settings.devCommand.value;if(defaults)return defaults}if((0,import_build_utils9.shouldUseExperimentalBackends)(frameworkSlug))return"npx @vercel/cervel dev"}}getFunctionDiscovery(options){let key=JSON.stringify(options);if(!this.functionDiscovery||this.functionDiscovery.key!==key){let promise=collectDevFunctions(options);this.functionDiscovery={key,promise},promise.catch(()=>{this.functionDiscovery?.promise===promise&&(this.functionDiscovery=void 0)})}return this.functionDiscovery.promise}getDevFunction(outputPath){return this.functionRegistry.functions.get(outputPath)}getDevSchedules(){return this.functionRegistry.schedules}async dispatchSchedule({delivery,signal}){if(signal.throwIfAborted(),this.stopping)throw new Error("Local Schedules is stopping");if(delivery.type==="queue"){if(!this.queueBroker)throw new Error("Local Queue broker is not ready");this.queueBroker.enqueue(delivery.topic,Buffer.from(JSON.stringify(delivery.message)),"application/json");return}if(delivery.type==="path"){if(!this.devProcessOrigin)throw new Error(`Schedule path "${delivery.path}" is not ready because the dev server is unavailable`);signal.throwIfAborted();let response=await directFetch(`${this.devProcessOrigin}${delivery.path}`,{method:delivery.requestMethod,signal});if(!response.ok)throw new Error(`Schedule path "${delivery.path}" returned HTTP ${response.status}`);return}let invoke=this.resolveDevFunction(delivery.function);if(!invoke)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);signal.throwIfAborted();let onAbort=()=>{},aborted=new Promise((_,reject)=>{onAbort=()=>reject(signal.reason),signal.addEventListener("abort",onAbort,{once:!0})});try{let result=await Promise.race([aborted,invoke({method:"POST",headers:delivery.headers,body:Buffer.alloc(0),signal})]);if(!result)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);if(!result.ok)throw new Error(`Schedule function "${delivery.function}" returned HTTP ${result.status}`)}finally{signal.removeEventListener("abort",onAbort)}}resolveDevFunction(outputPath){let fn2=this.getDevFunction(outputPath);if(!fn2||this.stopping)return null;if(fn2.invocation.type==="http"){if(!this.devProcessOrigin)return null}else if(!this.functionDispatchReady||this.functionReconciliations>0||!this.getDevFunctionMatch(fn2))return null;return request=>this.invokeDevFunction(outputPath,request)}getDevFunctionMatch(fn2){if(fn2.invocation.type!=="entrypoint"||fn2.scope.target!=="builder")return;let{entrypoint}=fn2.invocation;return[...this.buildMatches.values()].find(match=>match.entrypoint===entrypoint&&match.use===fn2.scope.build.use&&(0,import_fast_deep_equal.default)(match.config??{},fn2.scope.build.config??{}))}canonicalizeFunctionBuild(match){if(![...this.functionRegistry.functions.values()].some(fn2=>this.getDevFunctionMatch(fn2)===match))return!1;if(match.buildResults.size&&!(match.buildResults.size===1&&match.buildResults.has(null))){let results=[...match.buildResults.values()],result=results[results.length-1];result.watch=[...new Set(results.flatMap(result2=>result2.watch))],match.buildResults.clear(),match.buildResults.set(null,result)}return!0}async invokeDevFunction(outputPath,request){request.signal?.throwIfAborted();let fn2=this.getDevFunction(outputPath);if(!fn2||!this.resolveDevFunction(outputPath))return null;let generation=this.configGeneration,isCurrent=()=>!this.stopping&&generation===this.configGeneration&&this.getDevFunction(outputPath)===fn2;if(fn2.invocation.type==="http"){let response=await directFetch(`${this.devProcessOrigin}${fn2.invocation.pathname}`,{...request,redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}let match=this.getDevFunctionMatch(fn2),config=this.functionConfig,req=new http.IncomingMessage(new Socket);req.method=request.method,req.url=`/${outputPath}`,req.headers={host:this.address.host,...request.headers};let requestId=generateRequestId(this.podId,!0),currentMatch=()=>!request.signal?.aborted&&isCurrent()&&this.getDevFunctionMatch(fn2)===match,devServerResult=await this.startBuildMatchDevServer(match,outputPath);if(devServerResult){let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown);try{if(!currentMatch())return null;let response=await directFetch(`http://127.0.0.1:${port}/${outputPath}`,{...request,headers:nodeHeadersToFetchHeaders({...req.headers,...this.getProxyHeaders(req,requestId,!0)}),redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}finally{let current=this.getDevFunction(outputPath);(this.stopping||!persistent||!current||this.getDevFunctionMatch(current)!==match)&&this.shutdownCallbacks.has(pid)&&await this.killBuilderDevServer(pid)}}if(!currentMatch())return null;let{entrypoint}=fn2.invocation,getAsset=()=>match.buildOutput[(match.buildResultVersion??match.builderWithPkg.builder.version)===2?outputPath:entrypoint];this.canonicalizeFunctionBuild(match);let asset=getAsset();if((!asset||this.inProgressBuilds.get(match)?.size)&&(await this.triggerBuild(match,null,null,config),asset=getAsset()),!currentMatch())return null;if(!asset||asset.type!=="Lambda"||!asset.fn)return{ok:!1,status:404};let result=await this.invokeBuiltLambda(asset,req,requestId,request.body);return{ok:result.statusCode>=200&&result.statusCode<300,status:result.statusCode}}async startBuildMatchDevServer(match,requestPath){let{builder}=match.builderWithPkg;if(!builder.startDevServer)return null;let{envConfigs,files,devCacheDir,cwd:workPath}=this;return builder.startDevServer({files,entrypoint:match.entrypoint,workPath,config:match.config||{},repoRootPath:this.repoRoot,meta:{isDev:!0,...this.getDevResourceMeta(),requestPath,devCacheDir,...this.getSidecarDevMeta(match),env:this.getBuilderDevEnv(match,{...envConfigs.runEnv,VERCEL_DEBUG_PREFIX:output_manager_default.debugEnabled?"[builder]":void 0}),buildEnv:{...envConfigs.buildEnv}}})}invokeBuiltLambda(asset,req,requestId,body){let payload={method:req.method||"GET",host:req.headers.host,path:req.url||"/",headers:{...req.headers,...this.getProxyHeaders(req,requestId,!0)},encoding:"base64",body:body.toString("base64")};return asset.fn({Action:"Invoke",body:JSON.stringify(payload)})}async _getVercelConfig(){let generation=this.configGeneration,{compileVercelConfig}=await import("../../chunks/compile-vercel-config-4LNHE3YV.js"),compiled=await compileVercelConfig(this.cwd),configPath=getLocalPathConfig(this.cwd,!!compiled.sourceFile),[pkg=null,vercelConfig={version:2,[import_client.fileNameSymbol]:"vercel.json"}]=await Promise.all([this.readJsonFile("package.json"),this.readJsonFile(configPath,!0)]);await this.validateVercelConfig(vercelConfig);let functionConfig=structuredClone(vercelConfig),sourceFiles;for(let[name,service]of Object.entries(this.queueBroker?vercelConfig.services??vercelConfig.experimentalServicesV2??{}:{}))if(Object.values(service.functions??{}).some(fn2=>fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta")))throw dev.DEV_QUEUE_FUNCTION_UNSUPPORTED({sourceFile:`services.${name}.functions`,reason:"service-hosted function queue triggers are not supported locally yet"});let nextProjectSettings={...this.originalProjectSettings,...pickOverrides(vercelConfig)},{error:routeError,routes:maybeRoutes}=(0,import_routing_utils3.getTransformedRoutes)(vercelConfig);routeError&&(this.reportError(routeError),await this.exit()),vercelConfig.routes=maybeRoutes||[];let hasServices=(this.services?.length??0)>0,hasResolvedServices=!!this.services&&this.services.length>0,{schedules}=functionConfig,scheduleEntrypointPlan;if(!hasResolvedServices&&schedules?.some(import_schedule_entrypoint.hasScheduleEntrypointTarget)&&(sourceFiles=(await staticFiles(this.cwd,{})).map(f=>relative2(this.cwd,f)),scheduleEntrypointPlan=(0,import_schedule_entrypoint.planScheduleEntrypoints)({schedules,files:sourceFiles,framework:nextProjectSettings.framework,functions:functionConfig.functions})),!vercelConfig.experimentalServices&&!hasResolvedServices&&(!vercelConfig.builds||vercelConfig.builds.length===0)){let{projectSettings,cleanUrls,trailingSlash}=vercelConfig,files=sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative2(this.cwd,f));sourceFiles=files;let detectionOptions={tag:"latest",reservedFunctionFiles:scheduleEntrypointPlan?.reservedFunctionFiles,bunVersion:vercelConfig.bunVersion,functions:vercelConfig.functions,projectSettings:projectSettings||nextProjectSettings,featHandleMiss:!0,cleanUrls,trailingSlash,proxy:vercelConfig.proxy,workPath:this.cwd},detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions);for(;detectedBuilders.errors?.length===1&&detectedBuilders.errors[0].code==="unused_function";){let error2=detectedBuilders.errors[0],unmatchedTrigger=Object.entries(detectionOptions.functions??{}).find(([pattern,fn2])=>error2.message.startsWith(`The pattern "${pattern}" defined in \`functions\` `)&&fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta"||trigger.type==="schedule/v1beta"));if(!unmatchedTrigger)break;detectionOptions.functions={...detectionOptions.functions},delete detectionOptions.functions[unmatchedTrigger[0]],detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions)}let{builders,warnings,errors,defaultRoutes,redirectRoutes,rewriteRoutes,errorRoutes}=detectedBuilders,hostRewriteRoutes=detectedBuilders.hostRewriteRoutes;if(errors){if(this.functionConfig)throw errors[0];this.reportError(errors[0]),await this.exit()}if(warnings?.length>0&&warnings.forEach(warning=>output_manager_default.warn(warning.message,null,warning.link,warning.action)),builders){let buildpackRuntime=builders.map(getBuildpackRuntime).find(runtime=>runtime!==void 0);if(buildpackRuntime)throw buildpackDevUnsupportedError(buildpackRuntime);vercelConfig.builds=vercelConfig.builds||[],vercelConfig.builds.push(...builders),delete vercelConfig.functions}let serviceRewrites=detectedBuilders.serviceRewrites,serviceRewriteRoutes=serviceRewrites&&serviceRewrites.length>0?(0,import_routing_utils3.convertRewrites)(serviceRewrites):null,routes=[];routes.push(...redirectRoutes||[]),routes=(0,import_routing_utils3.appendRoutesToPhase)({routes,newRoutes:hostRewriteRoutes??null,phase:null}),routes.push(...(0,import_routing_utils3.appendRoutesToPhase)({routes:vercelConfig.routes,newRoutes:[...rewriteRoutes||[],...serviceRewriteRoutes||[]],phase:"filesystem"})),routes=(0,import_routing_utils3.appendRoutesToPhase)({routes,newRoutes:errorRoutes,phase:"error"}),routes.push(...defaultRoutes||[]),vercelConfig.routes=routes}else if(hasResolvedServices&&vercelConfig.proxy){let{entrypoint}=vercelConfig.proxy;await import_fs_extra.default.pathExists(join4(this.cwd,entrypoint))||(output_manager_default.error(`The proxy entrypoint \`${entrypoint}\` does not exist. Set \`proxy.entrypoint\` to an existing \`.js\` or \`.ts\` file.`),await this.exit()),vercelConfig.builds=vercelConfig.builds||[],vercelConfig.builds.push((0,import_fs_detectors2.getProxyBuilder)(vercelConfig.proxy,"latest",vercelConfig.functions))}if(this.sidecars===void 0){let services=(this.services??[]).filter(import_build_utils9.isExperimentalServiceV2);this.sidecars=await collectBuilderDevSidecars({builds:this.shouldUseServicesOrchestrator()?services.map(service=>service.builder):vercelConfig.builds??[],workPath:this.cwd,services})}scheduleEntrypointPlan&&(vercelConfig.builds??=[{src:"**",use:"@vercel/static"}],(0,import_schedule_entrypoint.assertNoScheduleEntrypointSourceConflict)(vercelConfig.builds,scheduleEntrypointPlan),vercelConfig.builds.push(...scheduleEntrypointPlan.builds));let functionBuilds=[...vercelConfig.builds??[]];Array.isArray(vercelConfig.builds)&&((this.getDevCommand(nextProjectSettings)||hasServices)&&(vercelConfig.builds=vercelConfig.builds.filter(this.shouldBuildInDev)),vercelConfig.builds.sort(sortBuilders)),vercelConfig.routes=(vercelConfig.routes||[]).filter(route=>"has"in route?(this.vercelConfigWarning||(this.vercelConfigWarning=!0,output_manager_default.warn(`The "has" property in ${vercelConfig[import_client.fileNameSymbol]} will be ignored during development. Deployments will work as expected.`)),!1):!0);let[runEnv,buildEnv]=await Promise.all([this.getLocalEnv(".env",vercelConfig.env),this.getLocalEnv(".env.build",vercelConfig.build?.env)]),allEnv={...buildEnv,...runEnv},envFromCloud=Object.keys(allEnv).length===0;if(envFromCloud){let envValues={...this.envValues};this.address.host&&(envValues.VERCEL_URL=this.address.host),allEnv={...envValues},runEnv={...envValues},buildEnv={...envValues}}runEnv.NODE_ENV??=process.env.NODE_ENV??"development",allEnv.NODE_ENV??=runEnv.NODE_ENV,runEnv.NOW_REGION="dev1",buildEnv.NOW_REGION="dev1",allEnv.NOW_REGION="dev1",allEnv.VERCEL_ENV="development",allEnv.VERCEL="1",this.projectId&&!process.env.VERCEL_PROJECT_ID&&("VERCEL_PROJECT_ID"in allEnv||(allEnv.VERCEL_PROJECT_ID=this.projectId),"VERCEL_PROJECT_ID"in runEnv||(runEnv.VERCEL_PROJECT_ID=this.projectId)),this.orgId&&!process.env.VERCEL_ORG_ID&&("VERCEL_ORG_ID"in allEnv||(allEnv.VERCEL_ORG_ID=this.orgId),"VERCEL_ORG_ID"in runEnv||(runEnv.VERCEL_ORG_ID=this.orgId)),nextProjectSettings?.autoExposeSystemEnvs&&(runEnv.VERCEL_REGION="dev1"),runEnv.VERCEL_CLI_VERSION=pkg_default.version,Object.assign(runEnv,this.getDevQueueEnv()),Object.assign(runEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(allEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(runEnv,this.getDevRuntimeCacheEnv(runEnv));let hasQueueFunctions=Object.values(functionConfig.functions??{}).some(fn2=>fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta"));if(this.queueBroker&&hasQueueFunctions&&hasResolvedServices)throw dev.DEV_QUEUE_FUNCTION_UNSUPPORTED({sourceFile:"functions",reason:"service-hosted function queue triggers are not supported locally yet"});let registry=await this.getFunctionDiscovery({scopes:(hasResolvedServices?[]:functionBuilds).map(build=>({build,target:vercelConfig.builds?.includes(build)?"builder":"framework"})),workPath:this.cwd,files:(sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative2(this.cwd,f))).sort(),config:functionConfig,env:{...process.env,...allEnv,...this.getDevQueueEnv(),...getDevSchedulesEnv(this.schedulesOrigin),...this.getDevRuntimeCacheEnv(allEnv)}}),subscriptions,staticSchedules,sourceChanged;try{subscriptions=deriveQueueSubscriptions(registry),this.queueBroker?.validateFunctionSubscriptions(subscriptions),staticSchedules=collectStaticSchedules(scheduleEntrypointPlan&&schedules?(0,import_schedule_entrypoint.resolveScheduleEntrypointTargets)(schedules,scheduleEntrypointPlan):functionConfig.schedules,registry),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&this.scheduleBroker.validateStatic(staticSchedules)}catch(err){throw this.functionDiscovery=void 0,err}let{unmatchedPatterns}=registry;if(await this.refreshBulkRedirects(vercelConfig.bulkRedirectsPath),this.devCommandStarts.size&&await Promise.all(this.devCommandStarts),this.stopping||generation!==this.configGeneration)return vercelConfig;let restartForFunctionEnv=!!(this.devCommandEnv&&[...registry.functions.values()].some(fn2=>fn2.invocation.type==="http")&&!(0,import_fast_deep_equal.default)(this.devCommandEnv,allEnv)),previousProcess=this.devProcess,previousOrigin=this.devProcessOrigin,previousCommand=this.currentDevCommand,previousEnv=this.devCommandEnv,previousRuntime={projectSettings:this.projectSettings,allEnv:previousEnv??this.envConfigs.allEnv},restarted,validated=!1;try{if(this.initialDevCommandStarted&&await this.runDevCommand(restartForFunctionEnv,{projectSettings:nextProjectSettings,allEnv},origin=>{restarted={origin}}),this.stopping||generation!==this.configGeneration)return vercelConfig;this.queueBroker?.validateFunctionSubscriptions(subscriptions),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&(this.scheduleBroker.validateStatic(staticSchedules),this.scheduleBroker.reconcileStatic(staticSchedules),this.staticSchedulesSnapshot=structuredClone(staticSchedules)),validated=!0}finally{!this.stopping&&!validated&&(this.devProcess!==previousProcess||this.devProcessOrigin!==previousOrigin||this.currentDevCommand!==previousCommand||this.devCommandEnv!==previousEnv)&&await this.runDevCommand(!0,previousRuntime)}this.projectSettings=nextProjectSettings,this.caseSensitive=hasNewRoutingProperties(vercelConfig),this.apiDir=(0,import_fs_detectors2.detectApiDirectory)(vercelConfig.builds||[]),this.apiExtensions=(0,import_fs_detectors2.detectApiExtensions)(vercelConfig.builds||[]),this.envConfigs={buildEnv,runEnv,allEnv},this.envFromCloud=envFromCloud,this.functionRegistry=registry,this.functionConfig=vercelConfig,restarted&&(this.devProcessOrigin=restarted.origin),this.queueBroker?.setFunctionSubscriptions(subscriptions,outputPath=>this.resolveDevFunction(outputPath));for(let pattern of unmatchedPatterns)if(!this.unmatchedQueuePatterns.has(pattern)){let warning=dev.DEV_QUEUE_FUNCTION_UNMATCHED({pattern});output_manager_default.warn(`[${warning.name}] ${warning.message} ${warning.fix}`)}return this.unmatchedQueuePatterns=new Set(unmatchedPatterns),vercelConfig}async refreshBulkRedirects(bulkRedirectsPath){let configPath=bulkRedirectsPath??null;if(configPath===this.bulkRedirectsLastPath&&!this.bulkRedirectsDirty)return;if(this.bulkRedirectsLastPath=configPath,this.bulkRedirectsDirty=!1,this.bulkRedirectsResolvedPath=configPath?resolveBulkRedirectsPath(this.cwd,configPath):null,!configPath){this.bulkRedirects=null,this.bulkRedirectsSignature=null;return}let signature=await getBulkRedirectsSignature(this.cwd,configPath);if(signature!==this.bulkRedirectsSignature){this.bulkRedirectsSignature=signature;try{let result=await loadBulkRedirects(this.cwd,configPath);this.bulkRedirects=result.table;for(let warning of result.warnings)output_manager_default.warn(warning);let count=result.table.size;count>0&&output_manager_default.log(`Loaded ${count} bulk ${(0,import_pluralize2.default)("redirect",count)} from ${configPath}`)}catch(err){this.bulkRedirects=null,output_manager_default.warn(`Failed to load bulk redirects from "${configPath}": ${(0,import_error_utils.errorToString)(err)}`)}}}async readJsonFile(filePath,strict=!1){let rel,abs;isAbsolute3(filePath)?(rel=path4.relative(this.cwd,filePath),abs=filePath):(rel=filePath,abs=join4(this.cwd,filePath)),output_manager_default.debug(`Reading \`${rel}\` file`);try{let raw=await import_fs_extra.default.readFile(abs,"utf8"),parsed=(0,import_json_parse_better_errors.default)(raw);return parsed[import_client.fileNameSymbol]=rel,parsed}catch(err){if(strict&&!((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT"))throw err;if((0,import_error_utils.isError)(err))(0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT"?output_manager_default.debug(`No \`${rel}\` file present`):err.name==="SyntaxError"&&output_manager_default.warn(`There is a syntax error in the \`${rel}\` file: ${err.message}`);else throw err}}async tryValidateOrExit(config,validate){let message2=validate(config);message2&&(output_manager_default.error(message2),await this.exit(1))}async validateVercelConfig(config){if(config.version===1){if(this.functionConfig)throw dev.DEV_UNSUPPORTED_CONFIG_VERSION();this.reportError(dev.DEV_UNSUPPORTED_CONFIG_VERSION()),await this.exit(1);return}let error2=validateConfig(config);if(error2){if(this.functionConfig)throw error2;this.reportError(error2),await this.exit(1)}}validateEnvConfig(type,env={},localEnv={}){let missing=Object.entries(env).filter(([name,value])=>typeof value=="string"&&value.startsWith("@")&&!hasProp(localEnv,name)).map(([name])=>name);if(missing.length>0)throw new MissingDotenvVarsError(type,missing);let merged={...env,...localEnv},hasInvalidName=!1;for(let key of Object.keys(merged))/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)||(output_manager_default.warn(`Ignoring ${type.split(".").slice(1).reverse().join(" ")} var ${JSON.stringify(key)} because name is invalid`),hasInvalidName=!0,delete merged[key]);return hasInvalidName&&output_manager_default.log("The name contains invalid characters. Only letters, digits, and underscores are allowed. Furthermore, the name should not start with a digit"),merged}injectSystemValuesInDotenv(env){for(let name of Object.keys(env))name==="VERCEL_URL"?env.VERCEL_URL=this.address.host:name==="VERCEL_REGION"&&(env.VERCEL_REGION="dev1");return env}resolveBuildFiles(files){return Object.keys(files).filter(this.filter)}isWatcherIgnored(fsPath){let relativePath=relative2(this.cwd,fsPath);return relativePath===""?!1:!this.filter(relativePath)}start(...listenSpec){return this.startPromise||(this.startPromise=this._start(...listenSpec).catch(async err=>{throw await this.stop(),err})),this.startPromise}async _start(...listenSpec){if(this.stopping)return;if(!import_fs_extra.default.existsSync(this.cwd))throw dev.DEV_CWD_NOT_FOUND({cwd:this.cwd});if(!import_fs_extra.default.lstatSync(this.cwd).isDirectory())throw dev.DEV_CWD_NOT_DIRECTORY({cwd:this.cwd});let{ig}=await(0,import_client.getVercelIgnore)(this.cwd);this.filter=ig.createFilter();let address=this.routing?null:`http://localhost:${this.devCommandPort}`;for(;typeof address!="string";){if(this.stopping)return;try{address=(await(this.listenerStartup=(0,import_async_listen.listen)(this.server,...listenSpec))).toString()}catch(err){if((0,import_error_utils.isErrnoException)(err))if(output_manager_default.debug(`Got listen error: ${err.code}`),err.code==="EADDRINUSE")typeof listenSpec[0]=="number"?(output_manager_default.note(`Requested port ${import_chalk2.default.yellow(String(listenSpec[0]))} is already in use`),listenSpec[0]++):(this.reportError(dev.DEV_LISTEN_ADDRESS_IN_USE({address:String(listenSpec[0])})),process.exit(1));else throw err;else throw err}}if(this.stopping)return;this._address=new URL2(replaceLocalhost(address)),this.runtimeCache=new RuntimeCacheStore;let devCommandPorts=this.devCommandPort?[this.devCommandPort]:[],runtimeCacheListener=await(this.listenerStartup=listenOnDevResourcePort(this.runtimeCacheServer,{name:"Runtime Cache",flag:"--runtime-cache-port",defaultPort:DEV_RUNTIME_CACHE_DEFAULT_PORT,port:this.runtimeCachePort,reservedPorts:[this.queuePort,this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT,...devCommandPorts].filter(port=>port!==void 0&&port!==0)}));if(this.stopping)return;this.runtimeCacheOrigin=runtimeCacheListener.origin,runtimeCacheListener.defaultPort!==void 0&&output_manager_default.warn(`Runtime Cache default port ${runtimeCacheListener.defaultPort} is unavailable; listening on ${runtimeCacheListener.port} instead.
55
+ Please ensure that ${cmd(err.path)} is properly installed`,err.link="https://vercel.link/command-not-found"),output_manager_default.prettyError(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}if(devServerResult){requestId=generateRequestId(this.podId,!0);let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown),persistent||res.once("close",()=>{this.killBuilderDevServer(pid)}),debug(`Proxying to "${builderPkg.name}" dev server (port=${port}, pid=${pid})`);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search});let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,`http://127.0.0.1:${port}`,this,requestId,!1)}else debug(`Skipping \`startDevServer()\` for ${match.entrypoint}`)}let foundAsset=findAsset(match,requestPath,vercelConfig);if(!foundAsset&&callLevel===0&&(await this.triggerBuild(match,buildRequestPath,req,vercelConfig),foundAsset=findAsset(match,requestPath,vercelConfig)),this.devProcessOrigin&&(!foundAsset||foundAsset&&foundAsset.asset.type!=="Lambda")){debug("Proxying to frontend dev server");let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,this.devProcessOrigin,this,requestId,!1)}if(!foundAsset){await this.send404(req,res,requestId);return}let{asset,assetKey}=foundAsset;switch(debug(`Serving asset: [${asset.type}] ${assetKey} ${asset.contentType||""}`),asset.type){case"FileFsRef":this.setResponseHeaders(res,requestId);let staticResHeaders={};applyResponseTransforms(staticResHeaders,responseTransforms??[]);for(let[name,value]of Object.entries(staticResHeaders))value!==void 0&&res.setHeader(name,value);return req.url=`/${basename(asset.fsPath)}`,serveStaticFile(req,res,dirname3(asset.fsPath),{headers:[{source:"**/*",headers:[{key:"Content-Type",value:asset.contentType||getMimeType(assetKey)}]}]});case"FileBlob":let headers2={"Content-Length":asset.data.length,"Content-Type":asset.contentType||getMimeType(assetKey)};applyResponseTransforms(headers2,responseTransforms??[]),this.setResponseHeaders(res,requestId,headers2),res.end(asset.data);return;case"Lambda":if(!asset.fn){await this.sendError(req,res,requestId,"INTERNAL_LAMBDA_NOT_FOUND");return}requestId=generateRequestId(this.podId,!0);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search}),applyRequestTransforms(req,requestTransforms);let path6=req.url||"/",body=await(0,import_raw_body2.default)(req);debug(`Invoking lambda: "${assetKey}" with ${path6}`);let result;try{result=await this.invokeBuiltLambda(asset,req,requestId,body)}catch(err){console.error(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}statusCode||(res.statusCode=result.statusCode);let lambdaHeaders=result.headers??{};applyResponseTransforms(lambdaHeaders,responseTransforms??[]),this.setResponseHeaders(res,requestId,lambdaHeaders);let resBody;return result.encoding==="base64"&&typeof result.body=="string"?resBody=Buffer.from(result.body,"base64"):resBody=result.body,res.end(resBody);default:await this.sendError(req,res,requestId,"UNKNOWN_ASSET_TYPE")}};if(this.cwd=cwd,this.repoRoot=options.repoRoot??cwd,this.envConfigs={buildEnv:{},runEnv:{},allEnv:{}},this.envValues=options.envValues||{},this.projectId=options.projectId,this.orgId=options.orgId,this.queuePort=options.queuePort,this.runtimeCachePort=options.runtimeCachePort,this.schedulesPort=options.schedulesPort,this.routing=options.routing??!0,this.devCommandPort=options.devCommandPort,!this.routing&&!this.devCommandPort)throw new Error("Running without the router needs a `devCommandPort`");this.scheduleBroker=new import_local_schedules2.ScheduleBroker({ownerId:this.orgId??"team_local",projectId:this.projectId??"prj_local",trackId:"development",dispatch:invocation=>this.dispatchSchedule(invocation),onError:(err,invocation)=>{try{output_manager_default.error(`Failed to dispatch schedule "${invocation.schedule.name}": ${(0,import_error_utils.errorToString)(err)}`)}catch{}}}),this.resourceProxyToken=randomBytes2(32).toString("base64url"),this.reportError=createErrorReporter2(code=>options.onErrorCode?.(code)),this.files={},this.originalProjectSettings=options.projectSettings,this.projectSettings=options.projectSettings,this.services=options.services,this.useImplicitServicesEnvInjection=options.useImplicitServicesEnvInjection??!0,this.caseSensitive=!1,this.apiDir=null,this.apiExtensions=new Set,this.proxy=import_http_proxy_node16.default.createProxyServer({changeOrigin:!0,ws:!0,xfwd:!0}),this.proxy.on("proxyRes",(proxyRes,req)=>{proxyRes.headers.server="Vercel";let responseTransforms=this.responseTransformsByReq.get(req);responseTransforms&&(this.responseTransformsByReq.delete(req),applyResponseTransforms(proxyRes.headers,responseTransforms))}),this.proxy.on("error",(err,req,res)=>{if(output_manager_default.debug(`Proxy error for ${req?.url??"unknown request"}: ${(0,import_error_utils.errorToString)(err)}`),!!res){if("destroy"in res&&typeof res.destroy=="function"){res.destroy();return}res instanceof http.ServerResponse&&(res.headersSent||res.writeHead(502),res.end())}}),this.server=http.createServer(this.devServerHandler),this.server.timeout=0,this.queueServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.queueOrigin,this.handleQueuesRoute)}),this.runtimeCacheServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.runtimeCacheOrigin,this.handleRuntimeCacheRoute)}),this.schedulesServer=http.createServer((req,res)=>{this.schedulesSession&&res.setHeader(LOCAL_SCHEDULES_SESSION_HEADER,this.schedulesSession.session.id),this.handleResourceServerRequest(req,res,this.schedulesOrigin,this.handleSchedulesRoute)}),this.stopping=!1,this.buildMatches=new Map,this.inProgressBuilds=new Map,this.devCacheDir=join4(getVercelDirectory(cwd),"cache"),this.vercelConfigWarning=!1,this.getVercelConfigPromise=null,this.blockingBuildsPromise=null,this.startPromise=null,this.bulkRedirects=null,this.bulkRedirectsSignature=null,this.bulkRedirectsLastPath=null,this.bulkRedirectsResolvedPath=null,this.bulkRedirectsDirty=!0,this.watchAggregationId=null,this.watchAggregationEvents=[],this.watchAggregationTimeout=500,this.filter=path6=>!!path6,this.podId=Math.random().toString(32).slice(-5),this.shutdownCallbacks=new Map}get address(){if(!this._address)throw dev.DEV_INTERNAL_ADDRESS_UNAVAILABLE();return this._address}shouldUseServicesOrchestrator(){return!!(this.services&&this.services.length>0)}hasSubscribers(){return!!this.sidecars?.length}getDevQueueEnv(){return this.queueOrigin?getDevQueueEnv(this.queueOrigin,this.hasSubscribers()):{}}getDevRuntimeCacheEnv(env){return!this.runtimeCacheOrigin||env.RUNTIME_CACHE_ENDPOINT?{}:process.env.RUNTIME_CACHE_ENDPOINT?{RUNTIME_CACHE_ENDPOINT:process.env.RUNTIME_CACHE_ENDPOINT,...process.env.RUNTIME_CACHE_HEADERS?{RUNTIME_CACHE_HEADERS:process.env.RUNTIME_CACHE_HEADERS}:{}}:getDevRuntimeCacheEnv(this.runtimeCacheOrigin,DEV_RUNTIME_CACHE_API_PREFIX)}get resourceEndpoints(){if(!this.queueOrigin||!this.runtimeCacheOrigin)throw new Error("Local resource servers have not started");let proxied=(direct,path6)=>this.routing?`${this.address.origin}${path6}`:direct,runtimeCache=`${this.runtimeCacheOrigin}${DEV_RUNTIME_CACHE_API_PREFIX}`;return{queues:{direct:this.queueOrigin,proxy:proxied(this.queueOrigin,`${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`)},runtimeCache:{direct:runtimeCache,proxy:proxied(runtimeCache,`${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}${DEV_RUNTIME_CACHE_API_PREFIX}`)},...this.schedulesOrigin?{schedules:{direct:this.schedulesOrigin,proxy:proxied(this.schedulesOrigin,`${DEV_SCHEDULES_PROXY_PREFIX}/${this.resourceProxyToken}`)}}:{}}}getDevResourceMeta(){return{devResourceEndpoints:this.resourceEndpoints}}handleResourceServerRequest(req,res,origin,handler){if(!origin||!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}if(!isValidDevResourceHost(origin,req.headers.host)){res.writeHead(403),res.end("Forbidden");return}let pathname=new URL2(req.url||"/","http://127.0.0.1").pathname;handler(req,res,pathname).catch(err=>{output_manager_default.debug(`Local resource request failed for ${req.url||"/"}: ${(0,import_error_utils.errorToString)(err)}`),res.headersSent||res.writeHead(500),res.end("Internal Server Error")})}isAuthorizedResourceRequest(req,token){let authorization=req.headers.authorization;if(typeof authorization!="string")return!1;let encoder=new TextEncoder,actual=encoder.encode(authorization),expected=encoder.encode(`Bearer ${token}`);return actual.length===expected.length&&timingSafeEqual(actual,expected)}getBuilderDevEnv(match,env){let result={...env,...getDevSchedulesEnv(this.schedulesOrigin)};if(match.builderWithPkg.pkg.name!=="@vercel/container")return result;let endpoints=this.resourceEndpoints;return Object.assign(result,getDevSchedulesEnv(endpoints.schedules?.proxy,!0)),result.VERCEL_QUEUE_BASE_URL===endpoints.queues.direct&&Object.assign(result,getDevQueueEnv(endpoints.queues.proxy,result.VERCEL_HAS_WORKER_SERVICES!==void 0)),result.RUNTIME_CACHE_ENDPOINT===endpoints.runtimeCache.direct&&Object.assign(result,getDevRuntimeCacheEnv(endpoints.runtimeCache.proxy,"")),result}getSidecarDevMeta(match){let serviceCount=(this.sidecars??[]).filter(sidecar=>sidecar.builder.use!==match.use?!1:!sidecar.workspace||sidecar.workspace===".").length;return serviceCount>0?{serviceCount}:{}}async setupBuilderDevSidecars(){if(this.shouldUseServicesOrchestrator())return;let sidecars=this.sidecars??[];if(sidecars.length===0)return;Object.assign(this.envConfigs.runEnv,this.getDevQueueEnv());let services=sidecars.map(toOrchestratorService),orchestrator=new ServicesOrchestrator({services,cwd:this.cwd,repoRoot:this.repoRoot,env:this.envConfigs.allEnv,proxyOrigin:this.address.origin,resourceEndpoints:this.resourceEndpoints,useImplicitEnvInjection:!1,preferServiceBuilder:!0,onQueueSubscriptions:(serviceName,subscriptions)=>this.queueBroker?.updateServiceSubscriptions(serviceName,subscriptions)});this.sidecarOrchestrator=orchestrator,this.queueBroker?.registerServices(services);try{await orchestrator.startAll()}catch(err){throw await orchestrator.stopAll(),this.sidecarOrchestrator=void 0,this.sidecars=[],err}output_manager_default.log(`Started ${sidecars.length} development ${(0,import_pluralize2.default)("sidecar",sidecars.length)}`)}async exit(code=1){await this.stop(code),process.exit(code)}enqueueFsEvent(type,path6){this.bulkRedirectsResolvedPath&&(path6===this.bulkRedirectsResolvedPath||path6.startsWith(this.bulkRedirectsResolvedPath+sep2))&&(this.bulkRedirectsDirty=!0),this.watchAggregationEvents.push({type,path:path6}),this.watchAggregationId===null&&(this.watchAggregationId=setTimeout(()=>{let events=this.watchAggregationEvents.slice();this.watchAggregationEvents.length=0,this.watchAggregationId=null,this.handleFilesystemEvents(events).catch(err=>{output_manager_default.prettyError(err),(0,import_error_utils.isError)(err)&&typeof err.stack=="string"&&output_manager_default.debug(err.stack)})},this.watchAggregationTimeout))}async handleFilesystemEvents(events){if(this.stopping)return;output_manager_default.debug(`Filesystem watcher notified of ${events.length} events`);let filesChanged=new Set,filesRemoved=new Set,distPaths=[];for(let buildMatch of this.buildMatches.values())for(let buildResult of buildMatch.buildResults.values())buildResult.distPath&&distPaths.push(buildResult.distPath);if(events=events.filter(event=>distPaths.every(distPath=>!event.path.startsWith(distPath))),events.length!==0){this.functionReconciliations++;try{this.configGeneration++,this.functionDiscovery=void 0;for(let event of events)event.type==="add"?await this.handleFileCreated(event.path,filesChanged,filesRemoved):event.type==="unlink"?this.handleFileDeleted(event.path,filesChanged,filesRemoved):event.type==="change"&&await this.handleFileModified(event.path,filesChanged,filesRemoved);let vercelConfig=await this.getVercelConfig();if(this.stopping)return;await this.updateBuildMatches(vercelConfig);let filesChangedArray=[...filesChanged],filesRemovedArray=[...filesRemoved],needsRebuild=new Map;for(let match of this.buildMatches.values()){this.canonicalizeFunctionBuild(match);for(let[requestPath,result]of match.buildResults)if(!needsRebuild.has(result)&&Array.isArray(result.watch)){for(let pattern of result.watch)if(minimatches(filesChangedArray,pattern)||minimatches(filesRemovedArray,pattern)){needsRebuild.set(result,[requestPath,match]);break}}}if(needsRebuild.size>0){output_manager_default.debug(`Triggering ${needsRebuild.size} rebuilds`),filesChangedArray.length>0&&output_manager_default.debug(`Files changed: ${filesChangedArray.join(", ")}`),filesRemovedArray.length>0&&output_manager_default.debug(`Files removed: ${filesRemovedArray.join(", ")}`);for(let[result,[requestPath,match]]of needsRebuild)requestPath===null||await shouldServe(match,this.files,requestPath,this,vercelConfig)?this.triggerBuild(match,requestPath,null,vercelConfig,result,filesChangedArray,filesRemovedArray).catch(err=>{output_manager_default.warn(`An error occurred while rebuilding \`${match.src}\`:`),console.error(err.stack)}):output_manager_default.debug(`Not rebuilding because \`shouldServe()\` returned \`false\` for "${match.use}" request path "${requestPath}"`)}}finally{this.functionReconciliations--}}}async handleFileCreated(fsPath,changed,removed){let name=relative2(this.cwd,fsPath);try{await this.getVercelConfig(),this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath});let extensionless=this.getExtensionlessFile(name);extensionless&&(this.files[extensionless]=await import_build_utils9.FileFsRef.fromFsPath({fsPath})),fileChanged(name,changed,removed),output_manager_default.debug(`File created: ${name}`)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File created, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}handleFileDeleted(fsPath,changed,removed){let name=relative2(this.cwd,fsPath);output_manager_default.debug(`File deleted: ${name}`),fileRemoved(name,this.files,changed,removed);let extensionless=this.getExtensionlessFile(name);extensionless&&(output_manager_default.debug(`File deleted: ${extensionless}`),fileRemoved(extensionless,this.files,changed,removed))}async handleFileModified(fsPath,changed,removed){let name=relative2(this.cwd,fsPath);try{this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath}),fileChanged(name,changed,removed),output_manager_default.debug(`File modified: ${name}`)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File modified, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}async updateBuildMatches(vercelConfig,isInitial=!1){let fileList=this.resolveBuildFiles(this.files),matches=await getBuildMatches(vercelConfig,this.cwd,this,fileList),sources=matches.map(m=>m.src);isInitial&&fileList.length===0&&output_manager_default.warn("There are no files inside your deployment.");let ops=[];for(let src of this.buildMatches.keys())if(!sources.includes(src)){output_manager_default.debug(`Removing build match for "${src}"`);let match=this.buildMatches.get(src);match&&ops.push(shutdownBuilder(match)),this.buildMatches.delete(src)}await Promise.all(ops);let blockingBuilds=[];for(let match of matches){let currentMatch=this.buildMatches.get(match.src);if(!buildMatchEquals(currentMatch,match)&&(output_manager_default.debug(`Adding build match for "${match.src}" with "${match.use}"`),this.buildMatches.set(match.src,match),!isInitial&&needsBlockingBuild(match))){let buildPromise=executeBuild(vercelConfig,this,this.files,match,null,!1);blockingBuilds.push(buildPromise)}}blockingBuilds.length>0&&(output_manager_default.debug(`Waiting for ${blockingBuilds.length} "blocking builds"`),this.blockingBuildsPromise=Promise.all(blockingBuilds).then(()=>{output_manager_default.debug('Cleaning up "blockingBuildsPromise" after successful resolve'),this.blockingBuildsPromise=null}).catch(err=>{output_manager_default.debug(`Cleaning up "blockingBuildsPromise" after error: ${err}`),this.blockingBuildsPromise=null,err&&output_manager_default.prettyError(err)})),this.buildMatches=new Map([...this.buildMatches.entries()].sort((matchA,matchB)=>sortBuilders(matchA[1],matchB[1])))}async getLocalEnv(fileName,base){let filePath=join4(this.cwd,fileName),env={};try{let dotenv=await import_fs_extra.default.readFile(filePath,"utf8");output_manager_default.debug(`Using local env: ${filePath}`),env=(0,import_dotenv.parse)(dotenv),env=this.injectSystemValuesInDotenv(env)}catch(err){if(!(0,import_error_utils.isErrnoException)(err)||err.code!=="ENOENT")throw err}try{return{...this.validateEnvConfig(fileName,base||{},env)}}catch(err){if(err instanceof MissingDotenvVarsError)this.reportError(err),await this.exit();else throw err}return{}}getVercelConfig(){if(this.getVercelConfigPromise)return this.getVercelConfigPromise;this.getVercelConfigPromise=(async()=>{for(;;){let generation=this.configGeneration;try{let config=await this._getVercelConfig();if(this.stopping||generation===this.configGeneration)return config}catch(err){if(this.stopping||generation===this.configGeneration)throw err}this.functionDiscovery=void 0}})();let clear=this.clearVercelConfigPromise;return this.getVercelConfigPromise.then(clear,clear),this.getVercelConfigPromise}get devCommand(){return this.getDevCommand(this.projectSettings)}get devCommandOrigin(){return this.devProcessOrigin}getDevCommand(projectSettings){if(projectSettings?.devCommand)return projectSettings.devCommand;if(projectSettings?.framework){let frameworkSlug=projectSettings.framework,framework=import_frameworks3.frameworkList.find(f=>f.slug===frameworkSlug);if(framework){let defaults=framework.settings.devCommand.value;if(defaults)return defaults}if((0,import_build_utils9.shouldUseExperimentalBackends)(frameworkSlug))return"npx @vercel/cervel dev"}}getFunctionDiscovery(options){let key=JSON.stringify(options);if(!this.functionDiscovery||this.functionDiscovery.key!==key){let promise=collectDevFunctions(options);this.functionDiscovery={key,promise},promise.catch(()=>{this.functionDiscovery?.promise===promise&&(this.functionDiscovery=void 0)})}return this.functionDiscovery.promise}getDevFunction(outputPath){return this.functionRegistry.functions.get(outputPath)}getDevSchedules(){return this.functionRegistry.schedules}async dispatchSchedule({delivery,signal}){if(signal.throwIfAborted(),this.stopping)throw new Error("Local Schedules is stopping");if(delivery.type==="queue"){if(!this.queueBroker)throw new Error("Local Queue broker is not ready");this.queueBroker.enqueue(delivery.topic,Buffer.from(JSON.stringify(delivery.message)),"application/json");return}if(delivery.type==="path"){if(!this.devProcessOrigin)throw new Error(`Schedule path "${delivery.path}" is not ready because the dev server is unavailable`);signal.throwIfAborted();let response=await directFetch(`${this.devProcessOrigin}${delivery.path}`,{method:delivery.requestMethod,signal});if(!response.ok)throw new Error(`Schedule path "${delivery.path}" returned HTTP ${response.status}`);return}let invoke=this.resolveDevFunction(delivery.function);if(!invoke)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);signal.throwIfAborted();let onAbort=()=>{},aborted=new Promise((_,reject)=>{onAbort=()=>reject(signal.reason),signal.addEventListener("abort",onAbort,{once:!0})});try{let result=await Promise.race([aborted,invoke({method:"POST",headers:delivery.headers,body:Buffer.alloc(0),signal})]);if(!result)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);if(!result.ok)throw new Error(`Schedule function "${delivery.function}" returned HTTP ${result.status}`)}finally{signal.removeEventListener("abort",onAbort)}}resolveDevFunction(outputPath){let fn2=this.getDevFunction(outputPath);if(!fn2||this.stopping)return null;if(fn2.invocation.type==="http"){if(!this.devProcessOrigin)return null}else if(!this.functionDispatchReady||this.functionReconciliations>0||!this.getDevFunctionMatch(fn2))return null;return request=>this.invokeDevFunction(outputPath,request)}getDevFunctionMatch(fn2){if(fn2.invocation.type!=="entrypoint"||fn2.scope.target!=="builder")return;let{entrypoint}=fn2.invocation;return[...this.buildMatches.values()].find(match=>match.entrypoint===entrypoint&&match.use===fn2.scope.build.use&&(0,import_fast_deep_equal.default)(match.config??{},fn2.scope.build.config??{}))}canonicalizeFunctionBuild(match){if(![...this.functionRegistry.functions.values()].some(fn2=>this.getDevFunctionMatch(fn2)===match))return!1;if(match.buildResults.size&&!(match.buildResults.size===1&&match.buildResults.has(null))){let results=[...match.buildResults.values()],result=results[results.length-1];result.watch=[...new Set(results.flatMap(result2=>result2.watch))],match.buildResults.clear(),match.buildResults.set(null,result)}return!0}async invokeDevFunction(outputPath,request){request.signal?.throwIfAborted();let fn2=this.getDevFunction(outputPath);if(!fn2||!this.resolveDevFunction(outputPath))return null;let generation=this.configGeneration,isCurrent=()=>!this.stopping&&generation===this.configGeneration&&this.getDevFunction(outputPath)===fn2;if(fn2.invocation.type==="http"){let response=await directFetch(`${this.devProcessOrigin}${fn2.invocation.pathname}`,{...request,redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}let match=this.getDevFunctionMatch(fn2),config=this.functionConfig,req=new http.IncomingMessage(new Socket);req.method=request.method,req.url=`/${outputPath}`,req.headers={host:this.address.host,...request.headers};let requestId=generateRequestId(this.podId,!0),currentMatch=()=>!request.signal?.aborted&&isCurrent()&&this.getDevFunctionMatch(fn2)===match,devServerResult=await this.startBuildMatchDevServer(match,outputPath);if(devServerResult){let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown);try{if(!currentMatch())return null;let response=await directFetch(`http://127.0.0.1:${port}/${outputPath}`,{...request,headers:nodeHeadersToFetchHeaders({...req.headers,...this.getProxyHeaders(req,requestId,!0)}),redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}finally{let current=this.getDevFunction(outputPath);(this.stopping||!persistent||!current||this.getDevFunctionMatch(current)!==match)&&this.shutdownCallbacks.has(pid)&&await this.killBuilderDevServer(pid)}}if(!currentMatch())return null;let{entrypoint}=fn2.invocation,getAsset=()=>match.buildOutput[(match.buildResultVersion??match.builderWithPkg.builder.version)===2?outputPath:entrypoint];this.canonicalizeFunctionBuild(match);let asset=getAsset();if((!asset||this.inProgressBuilds.get(match)?.size)&&(await this.triggerBuild(match,null,null,config),asset=getAsset()),!currentMatch())return null;if(!asset||asset.type!=="Lambda"||!asset.fn)return{ok:!1,status:404};let result=await this.invokeBuiltLambda(asset,req,requestId,request.body);return{ok:result.statusCode>=200&&result.statusCode<300,status:result.statusCode}}async startBuildMatchDevServer(match,requestPath){let{builder}=match.builderWithPkg;if(!builder.startDevServer)return null;let{envConfigs,files,devCacheDir,cwd:workPath}=this;return builder.startDevServer({files,entrypoint:match.entrypoint,workPath,config:match.config||{},repoRootPath:this.repoRoot,meta:{isDev:!0,...this.getDevResourceMeta(),requestPath,devCacheDir,...this.getSidecarDevMeta(match),env:this.getBuilderDevEnv(match,{...envConfigs.runEnv,VERCEL_DEBUG_PREFIX:output_manager_default.debugEnabled?"[builder]":void 0}),buildEnv:{...envConfigs.buildEnv}}})}invokeBuiltLambda(asset,req,requestId,body){let payload={method:req.method||"GET",host:req.headers.host,path:req.url||"/",headers:{...req.headers,...this.getProxyHeaders(req,requestId,!0)},encoding:"base64",body:body.toString("base64")};return asset.fn({Action:"Invoke",body:JSON.stringify(payload)})}async _getVercelConfig(){let generation=this.configGeneration,{compileVercelConfig}=await import("../../chunks/compile-vercel-config-ADKZDUAU.js"),compiled=await compileVercelConfig(this.cwd),configPath=getLocalPathConfig(this.cwd,!!compiled.sourceFile),[pkg=null,vercelConfig={version:2,[import_client.fileNameSymbol]:"vercel.json"}]=await Promise.all([this.readJsonFile("package.json"),this.readJsonFile(configPath,!0)]);await this.validateVercelConfig(vercelConfig);let functionConfig=structuredClone(vercelConfig),sourceFiles;for(let[name,service]of Object.entries(this.queueBroker?vercelConfig.services??vercelConfig.experimentalServicesV2??{}:{}))if(Object.values(service.functions??{}).some(fn2=>fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta")))throw dev.DEV_QUEUE_FUNCTION_UNSUPPORTED({sourceFile:`services.${name}.functions`,reason:"service-hosted function queue triggers are not supported locally yet"});let nextProjectSettings={...this.originalProjectSettings,...pickOverrides(vercelConfig)},{error:routeError,routes:maybeRoutes}=(0,import_routing_utils3.getTransformedRoutes)(vercelConfig);routeError&&(this.reportError(routeError),await this.exit()),vercelConfig.routes=maybeRoutes||[];let hasServices=(this.services?.length??0)>0,hasResolvedServices=!!this.services&&this.services.length>0,{schedules}=functionConfig,scheduleEntrypointPlan;if(!hasResolvedServices&&schedules?.some(import_schedule_entrypoint.hasScheduleEntrypointTarget)&&(sourceFiles=(await staticFiles(this.cwd,{})).map(f=>relative2(this.cwd,f)),scheduleEntrypointPlan=(0,import_schedule_entrypoint.planScheduleEntrypoints)({schedules,files:sourceFiles,framework:nextProjectSettings.framework,functions:functionConfig.functions})),!vercelConfig.experimentalServices&&!hasResolvedServices&&(!vercelConfig.builds||vercelConfig.builds.length===0)){let{projectSettings,cleanUrls,trailingSlash}=vercelConfig,files=sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative2(this.cwd,f));sourceFiles=files;let detectionOptions={tag:"latest",reservedFunctionFiles:scheduleEntrypointPlan?.reservedFunctionFiles,bunVersion:vercelConfig.bunVersion,functions:vercelConfig.functions,projectSettings:projectSettings||nextProjectSettings,featHandleMiss:!0,cleanUrls,trailingSlash,proxy:vercelConfig.proxy,workPath:this.cwd},detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions);for(;detectedBuilders.errors?.length===1&&detectedBuilders.errors[0].code==="unused_function";){let error2=detectedBuilders.errors[0],unmatchedTrigger=Object.entries(detectionOptions.functions??{}).find(([pattern,fn2])=>error2.message.startsWith(`The pattern "${pattern}" defined in \`functions\` `)&&fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta"||trigger.type==="schedule/v1beta"));if(!unmatchedTrigger)break;detectionOptions.functions={...detectionOptions.functions},delete detectionOptions.functions[unmatchedTrigger[0]],detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions)}let{builders,warnings,errors,defaultRoutes,redirectRoutes,rewriteRoutes,errorRoutes}=detectedBuilders,hostRewriteRoutes=detectedBuilders.hostRewriteRoutes;if(errors){if(this.functionConfig)throw errors[0];this.reportError(errors[0]),await this.exit()}if(warnings?.length>0&&warnings.forEach(warning=>output_manager_default.warn(warning.message,null,warning.link,warning.action)),builders){let buildpackRuntime=builders.map(getBuildpackRuntime).find(runtime=>runtime!==void 0);if(buildpackRuntime)throw buildpackDevUnsupportedError(buildpackRuntime);vercelConfig.builds=vercelConfig.builds||[],vercelConfig.builds.push(...builders),delete vercelConfig.functions}let serviceRewrites=detectedBuilders.serviceRewrites,serviceRewriteRoutes=serviceRewrites&&serviceRewrites.length>0?(0,import_routing_utils3.convertRewrites)(serviceRewrites):null,routes=[];routes.push(...redirectRoutes||[]),routes=(0,import_routing_utils3.appendRoutesToPhase)({routes,newRoutes:hostRewriteRoutes??null,phase:null}),routes.push(...(0,import_routing_utils3.appendRoutesToPhase)({routes:vercelConfig.routes,newRoutes:[...rewriteRoutes||[],...serviceRewriteRoutes||[]],phase:"filesystem"})),routes=(0,import_routing_utils3.appendRoutesToPhase)({routes,newRoutes:errorRoutes,phase:"error"}),routes.push(...defaultRoutes||[]),vercelConfig.routes=routes}else if(hasResolvedServices&&vercelConfig.proxy){let{entrypoint}=vercelConfig.proxy;await import_fs_extra.default.pathExists(join4(this.cwd,entrypoint))||(output_manager_default.error(`The proxy entrypoint \`${entrypoint}\` does not exist. Set \`proxy.entrypoint\` to an existing \`.js\` or \`.ts\` file.`),await this.exit()),vercelConfig.builds=vercelConfig.builds||[],vercelConfig.builds.push((0,import_fs_detectors2.getProxyBuilder)(vercelConfig.proxy,"latest",vercelConfig.functions))}if(this.sidecars===void 0){let services=(this.services??[]).filter(import_build_utils9.isExperimentalServiceV2);this.sidecars=await collectBuilderDevSidecars({builds:this.shouldUseServicesOrchestrator()?services.map(service=>service.builder):vercelConfig.builds??[],workPath:this.cwd,services})}scheduleEntrypointPlan&&(vercelConfig.builds??=[{src:"**",use:"@vercel/static"}],(0,import_schedule_entrypoint.assertNoScheduleEntrypointSourceConflict)(vercelConfig.builds,scheduleEntrypointPlan),vercelConfig.builds.push(...scheduleEntrypointPlan.builds));let functionBuilds=[...vercelConfig.builds??[]];Array.isArray(vercelConfig.builds)&&((this.getDevCommand(nextProjectSettings)||hasServices)&&(vercelConfig.builds=vercelConfig.builds.filter(this.shouldBuildInDev)),vercelConfig.builds.sort(sortBuilders)),vercelConfig.routes=(vercelConfig.routes||[]).filter(route=>"has"in route?(this.vercelConfigWarning||(this.vercelConfigWarning=!0,output_manager_default.warn(`The "has" property in ${vercelConfig[import_client.fileNameSymbol]} will be ignored during development. Deployments will work as expected.`)),!1):!0);let[runEnv,buildEnv]=await Promise.all([this.getLocalEnv(".env",vercelConfig.env),this.getLocalEnv(".env.build",vercelConfig.build?.env)]),allEnv={...buildEnv,...runEnv},envFromCloud=Object.keys(allEnv).length===0;if(envFromCloud){let envValues={...this.envValues};this.address.host&&(envValues.VERCEL_URL=this.address.host),allEnv={...envValues},runEnv={...envValues},buildEnv={...envValues}}runEnv.NODE_ENV??=process.env.NODE_ENV??"development",allEnv.NODE_ENV??=runEnv.NODE_ENV,runEnv.NOW_REGION="dev1",buildEnv.NOW_REGION="dev1",allEnv.NOW_REGION="dev1",allEnv.VERCEL_ENV="development",allEnv.VERCEL="1",this.projectId&&!process.env.VERCEL_PROJECT_ID&&("VERCEL_PROJECT_ID"in allEnv||(allEnv.VERCEL_PROJECT_ID=this.projectId),"VERCEL_PROJECT_ID"in runEnv||(runEnv.VERCEL_PROJECT_ID=this.projectId)),this.orgId&&!process.env.VERCEL_ORG_ID&&("VERCEL_ORG_ID"in allEnv||(allEnv.VERCEL_ORG_ID=this.orgId),"VERCEL_ORG_ID"in runEnv||(runEnv.VERCEL_ORG_ID=this.orgId)),nextProjectSettings?.autoExposeSystemEnvs&&(runEnv.VERCEL_REGION="dev1"),runEnv.VERCEL_CLI_VERSION=pkg_default.version,Object.assign(runEnv,this.getDevQueueEnv()),Object.assign(runEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(allEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(runEnv,this.getDevRuntimeCacheEnv(runEnv));let hasQueueFunctions=Object.values(functionConfig.functions??{}).some(fn2=>fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta"));if(this.queueBroker&&hasQueueFunctions&&hasResolvedServices)throw dev.DEV_QUEUE_FUNCTION_UNSUPPORTED({sourceFile:"functions",reason:"service-hosted function queue triggers are not supported locally yet"});let registry=await this.getFunctionDiscovery({scopes:(hasResolvedServices?[]:functionBuilds).map(build=>({build,target:vercelConfig.builds?.includes(build)?"builder":"framework"})),workPath:this.cwd,files:(sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative2(this.cwd,f))).sort(),config:functionConfig,env:{...process.env,...allEnv,...this.getDevQueueEnv(),...getDevSchedulesEnv(this.schedulesOrigin),...this.getDevRuntimeCacheEnv(allEnv)}}),subscriptions,staticSchedules,sourceChanged;try{subscriptions=deriveQueueSubscriptions(registry),this.queueBroker?.validateFunctionSubscriptions(subscriptions),staticSchedules=collectStaticSchedules(scheduleEntrypointPlan&&schedules?(0,import_schedule_entrypoint.resolveScheduleEntrypointTargets)(schedules,scheduleEntrypointPlan):functionConfig.schedules,registry),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&this.scheduleBroker.validateStatic(staticSchedules)}catch(err){throw this.functionDiscovery=void 0,err}let{unmatchedPatterns}=registry;if(await this.refreshBulkRedirects(vercelConfig.bulkRedirectsPath),this.devCommandStarts.size&&await Promise.all(this.devCommandStarts),this.stopping||generation!==this.configGeneration)return vercelConfig;let restartForFunctionEnv=!!(this.devCommandEnv&&[...registry.functions.values()].some(fn2=>fn2.invocation.type==="http")&&!(0,import_fast_deep_equal.default)(this.devCommandEnv,allEnv)),previousProcess=this.devProcess,previousOrigin=this.devProcessOrigin,previousCommand=this.currentDevCommand,previousEnv=this.devCommandEnv,previousRuntime={projectSettings:this.projectSettings,allEnv:previousEnv??this.envConfigs.allEnv},restarted,validated=!1;try{if(this.initialDevCommandStarted&&await this.runDevCommand(restartForFunctionEnv,{projectSettings:nextProjectSettings,allEnv},origin=>{restarted={origin}}),this.stopping||generation!==this.configGeneration)return vercelConfig;this.queueBroker?.validateFunctionSubscriptions(subscriptions),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&(this.scheduleBroker.validateStatic(staticSchedules),this.scheduleBroker.reconcileStatic(staticSchedules),this.staticSchedulesSnapshot=structuredClone(staticSchedules)),validated=!0}finally{!this.stopping&&!validated&&(this.devProcess!==previousProcess||this.devProcessOrigin!==previousOrigin||this.currentDevCommand!==previousCommand||this.devCommandEnv!==previousEnv)&&await this.runDevCommand(!0,previousRuntime)}this.projectSettings=nextProjectSettings,this.caseSensitive=hasNewRoutingProperties(vercelConfig),this.apiDir=(0,import_fs_detectors2.detectApiDirectory)(vercelConfig.builds||[]),this.apiExtensions=(0,import_fs_detectors2.detectApiExtensions)(vercelConfig.builds||[]),this.envConfigs={buildEnv,runEnv,allEnv},this.envFromCloud=envFromCloud,this.functionRegistry=registry,this.functionConfig=vercelConfig,restarted&&(this.devProcessOrigin=restarted.origin),this.queueBroker?.setFunctionSubscriptions(subscriptions,outputPath=>this.resolveDevFunction(outputPath));for(let pattern of unmatchedPatterns)if(!this.unmatchedQueuePatterns.has(pattern)){let warning=dev.DEV_QUEUE_FUNCTION_UNMATCHED({pattern});output_manager_default.warn(`[${warning.name}] ${warning.message} ${warning.fix}`)}return this.unmatchedQueuePatterns=new Set(unmatchedPatterns),vercelConfig}async refreshBulkRedirects(bulkRedirectsPath){let configPath=bulkRedirectsPath??null;if(configPath===this.bulkRedirectsLastPath&&!this.bulkRedirectsDirty)return;if(this.bulkRedirectsLastPath=configPath,this.bulkRedirectsDirty=!1,this.bulkRedirectsResolvedPath=configPath?resolveBulkRedirectsPath(this.cwd,configPath):null,!configPath){this.bulkRedirects=null,this.bulkRedirectsSignature=null;return}let signature=await getBulkRedirectsSignature(this.cwd,configPath);if(signature!==this.bulkRedirectsSignature){this.bulkRedirectsSignature=signature;try{let result=await loadBulkRedirects(this.cwd,configPath);this.bulkRedirects=result.table;for(let warning of result.warnings)output_manager_default.warn(warning);let count=result.table.size;count>0&&output_manager_default.log(`Loaded ${count} bulk ${(0,import_pluralize2.default)("redirect",count)} from ${configPath}`)}catch(err){this.bulkRedirects=null,output_manager_default.warn(`Failed to load bulk redirects from "${configPath}": ${(0,import_error_utils.errorToString)(err)}`)}}}async readJsonFile(filePath,strict=!1){let rel,abs;isAbsolute3(filePath)?(rel=path4.relative(this.cwd,filePath),abs=filePath):(rel=filePath,abs=join4(this.cwd,filePath)),output_manager_default.debug(`Reading \`${rel}\` file`);try{let raw=await import_fs_extra.default.readFile(abs,"utf8"),parsed=(0,import_json_parse_better_errors.default)(raw);return parsed[import_client.fileNameSymbol]=rel,parsed}catch(err){if(strict&&!((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT"))throw err;if((0,import_error_utils.isError)(err))(0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT"?output_manager_default.debug(`No \`${rel}\` file present`):err.name==="SyntaxError"&&output_manager_default.warn(`There is a syntax error in the \`${rel}\` file: ${err.message}`);else throw err}}async tryValidateOrExit(config,validate){let message2=validate(config);message2&&(output_manager_default.error(message2),await this.exit(1))}async validateVercelConfig(config){if(config.version===1){if(this.functionConfig)throw dev.DEV_UNSUPPORTED_CONFIG_VERSION();this.reportError(dev.DEV_UNSUPPORTED_CONFIG_VERSION()),await this.exit(1);return}let error2=validateConfig(config);if(error2){if(this.functionConfig)throw error2;this.reportError(error2),await this.exit(1)}}validateEnvConfig(type,env={},localEnv={}){let missing=Object.entries(env).filter(([name,value])=>typeof value=="string"&&value.startsWith("@")&&!hasProp(localEnv,name)).map(([name])=>name);if(missing.length>0)throw new MissingDotenvVarsError(type,missing);let merged={...env,...localEnv},hasInvalidName=!1;for(let key of Object.keys(merged))/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)||(output_manager_default.warn(`Ignoring ${type.split(".").slice(1).reverse().join(" ")} var ${JSON.stringify(key)} because name is invalid`),hasInvalidName=!0,delete merged[key]);return hasInvalidName&&output_manager_default.log("The name contains invalid characters. Only letters, digits, and underscores are allowed. Furthermore, the name should not start with a digit"),merged}injectSystemValuesInDotenv(env){for(let name of Object.keys(env))name==="VERCEL_URL"?env.VERCEL_URL=this.address.host:name==="VERCEL_REGION"&&(env.VERCEL_REGION="dev1");return env}resolveBuildFiles(files){return Object.keys(files).filter(this.filter)}isWatcherIgnored(fsPath){let relativePath=relative2(this.cwd,fsPath);return relativePath===""?!1:!this.filter(relativePath)}start(...listenSpec){return this.startPromise||(this.startPromise=this._start(...listenSpec).catch(async err=>{throw await this.stop(),err})),this.startPromise}async _start(...listenSpec){if(this.stopping)return;if(!import_fs_extra.default.existsSync(this.cwd))throw dev.DEV_CWD_NOT_FOUND({cwd:this.cwd});if(!import_fs_extra.default.lstatSync(this.cwd).isDirectory())throw dev.DEV_CWD_NOT_DIRECTORY({cwd:this.cwd});let{ig}=await(0,import_client.getVercelIgnore)(this.cwd);this.filter=ig.createFilter();let address=this.routing?null:`http://localhost:${this.devCommandPort}`;for(;typeof address!="string";){if(this.stopping)return;try{address=(await(this.listenerStartup=(0,import_async_listen.listen)(this.server,...listenSpec))).toString()}catch(err){if((0,import_error_utils.isErrnoException)(err))if(output_manager_default.debug(`Got listen error: ${err.code}`),err.code==="EADDRINUSE")typeof listenSpec[0]=="number"?(output_manager_default.note(`Requested port ${import_chalk2.default.yellow(String(listenSpec[0]))} is already in use`),listenSpec[0]++):(this.reportError(dev.DEV_LISTEN_ADDRESS_IN_USE({address:String(listenSpec[0])})),process.exit(1));else throw err;else throw err}}if(this.stopping)return;this._address=new URL2(replaceLocalhost(address)),this.runtimeCache=new RuntimeCacheStore;let devCommandPorts=this.devCommandPort?[this.devCommandPort]:[],runtimeCacheListener=await(this.listenerStartup=listenOnDevResourcePort(this.runtimeCacheServer,{name:"Runtime Cache",flag:"--runtime-cache-port",defaultPort:DEV_RUNTIME_CACHE_DEFAULT_PORT,port:this.runtimeCachePort,reservedPorts:[this.queuePort,this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT,...devCommandPorts].filter(port=>port!==void 0&&port!==0)}));if(this.stopping)return;this.runtimeCacheOrigin=runtimeCacheListener.origin,runtimeCacheListener.defaultPort!==void 0&&output_manager_default.warn(`Runtime Cache default port ${runtimeCacheListener.defaultPort} is unavailable; listening on ${runtimeCacheListener.port} instead.
56
56
  External clients configured for ${runtimeCacheListener.defaultPort} will not reach this dev server. Pin a port with --runtime-cache-port.`);let queueListener=await(this.listenerStartup=listenOnDevResourcePort(this.queueServer,{name:"Vercel Queues",flag:"--queue-port",defaultPort:DEV_QUEUE_DEFAULT_PORT,port:this.queuePort,reservedPorts:[this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT,...devCommandPorts]}));if(this.stopping)return;this.queueOrigin=queueListener.origin,queueListener.defaultPort!==void 0&&output_manager_default.warn(`Vercel Queues default port ${queueListener.defaultPort} is unavailable; listening on ${queueListener.port} instead.
57
57
  External clients configured for ${queueListener.defaultPort} will not reach this dev server. Pin a port with --queue-port.`),this.queueBroker=new QueueBroker([],name=>this.orchestrator?.getServiceOrigin(name)??this.sidecarOrchestrator?.getServiceOrigin(name)??null);let schedulesListener=await(this.listenerStartup=listenOnDevResourcePort(this.schedulesServer,{name:"Vercel Schedules",flag:"--schedules-port",defaultPort:DEV_SCHEDULES_DEFAULT_PORT,port:this.schedulesPort,reservedPorts:devCommandPorts}));if(this.stopping||(this.schedulesOrigin=schedulesListener.origin,this.schedulesSessionPublication=createLocalSchedulesSession(this.cwd,`http://127.0.0.1:${schedulesListener.port}`,this.projectId??"prj_local").then(async published=>{this.stopping?await published.dispose():this.schedulesSession=published}),await this.schedulesSessionPublication,this.stopping))return;schedulesListener.defaultPort!==void 0&&output_manager_default.print(import_chalk2.default.yellow(`! Vercel Schedules default port ${schedulesListener.defaultPort} is unavailable; listening on ${schedulesListener.port} instead.
58
58
  Pin a port with --schedules-port for clients outside the dev server.
@@ -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{CHECKBOX_INSTRUCTIONS,getCustomEnvironments,readStandardInput,require_dist as require_dist3}from"../../chunks/chunk-6JGC4YDH.js";import{getInvalidSubcommand}from"../../chunks/chunk-TG2RCYTH.js";import{ellipsis}from"../../chunks/chunk-F4KY2TOK.js";import{formatTable}from"../../chunks/chunk-LSQREJXO.js";import"../../chunks/chunk-ID663OJ7.js";import{autoInstallVercelPlugin}from"../../chunks/chunk-N7L3XLWC.js";import{require_execa}from"../../chunks/chunk-GSOPJJO5.js";import{ENV_VISIBILITY_DEPRECATION_MESSAGE,SENSITIVE_ENV_VALUE_PLACEHOLDER,formatVisibilityLabel,getApiPublicPrefix,getEnvKeyWarnings,getFrameworkPublicPrefix,getLocalSecretFallbackMessage,getLocalSvelteKitPublicPrefixes,getPublicPrefix,getPublicPrefixSecretVisibilityError,getUnavailableSecretValuesMessage,isFlagsSecretNeedingSplit,isSecretEnvVar,looksLikeSecret,looksLikeSecretValue,normalizeStdinEnvValue,pull,removePublicPrefix,resolveEnvVarTypeOption,resolveEnvVarVisibility,shouldConfirmRotationBeforeDelete,validateEnvValue}from"../../chunks/chunk-SRAC7DI4.js";import{resolveProjectContext}from"../../chunks/chunk-EKUHN42H.js";import"../../chunks/chunk-25565AGS.js";import{isGuidanceEnabled,suggestNextCommands}from"../../chunks/chunk-A5R2HHNK.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-J24BABG4.js";import{getEnvRecords,pullEnvRecords}from"../../chunks/chunk-YP46QVEI.js";import"../../chunks/chunk-5JEU6QSM.js";import"../../chunks/chunk-3GSGG4YR.js";import"../../chunks/chunk-PVASGBEF.js";import"../../chunks/chunk-MVCAUS4F.js";import{getCommandAliases}from"../../chunks/chunk-EEZLBOSP.js";import"../../chunks/chunk-ZBDLYNUF.js";import"../../chunks/chunk-J6O6JW2K.js";import"../../chunks/chunk-2FHICLHJ.js";import"../../chunks/chunk-2UMWTCY7.js";import"../../chunks/chunk-Q5ZGA2RO.js";import"../../chunks/chunk-UGMTKOTN.js";import"../../chunks/chunk-BTCKMXWW.js";import"../../chunks/chunk-ITKS32PG.js";import"../../chunks/chunk-CN3IVZJO.js";import"../../chunks/chunk-Y24OSBXP.js";import"../../chunks/chunk-GVVIFYQE.js";import"../../chunks/chunk-W3TGCMRW.js";import"../../chunks/chunk-B4YYOSPY.js";import"../../chunks/chunk-LD5U73LA.js";import"../../chunks/chunk-X65QKYDM.js";import"../../chunks/chunk-TPVAPVQC.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-FBYA6LLM.js";import{addSubcommand,envCommand,envTargetChoices,getEnvTargetPlaceholder,isValidEnvTarget,listSubcommand,parseEnvTargetArg,pullSubcommand,removeSubcommand,runSubcommand,updateSubcommand}from"../../chunks/chunk-WE3ZJX7P.js";import"../../chunks/chunk-DYQXJCHO.js";import"../../chunks/chunk-SCV7XEEO.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import{formatEnvironment}from"../../chunks/chunk-JSBEAHKA.js";import{validateLsArgs}from"../../chunks/chunk-EO7GUARB.js";import{STANDARD_ENVIRONMENTS,formatProject}from"../../chunks/chunk-3EYOQC4R.js";import"../../chunks/chunk-Q7D7RGXM.js";import{parseTarget}from"../../chunks/chunk-XEQT373M.js";import"../../chunks/chunk-J2LAZELI.js";import"../../chunks/chunk-E6UKNYFF.js";import"../../chunks/chunk-UCAE5Z5L.js";import{help}from"../../chunks/chunk-4GL254L4.js";import"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-3EU7MN5M.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{validateJsonOutput}from"../../chunks/chunk-D4MW3RDW.js";import"../../chunks/chunk-WZ7YJDKT.js";import{TelemetryClient,require_dist as require_dist2}from"../../chunks/chunk-JNJOUMGF.js";import"../../chunks/chunk-PAN6TUTQ.js";import"../../chunks/chunk-VKXEOL4K.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import"../../chunks/chunk-NWGBDBZI.js";import"../../chunks/chunk-4SAVH3H7.js";import"../../chunks/chunk-ZS2WS4AM.js";import"../../chunks/chunk-AOWWC6WZ.js";import"../../chunks/chunk-MY4MONOH.js";import{parseArguments}from"../../chunks/chunk-CRQDQNQZ.js";import{buildCommandWithYes,buildEnvAddCommandWithPreservedArgs,buildEnvRmCommandWithPreservedArgs,buildEnvUpdateCommandWithPreservedArgs,getPreservedArgsForEnvAdd,getPreservedArgsForEnvRm,getPreservedArgsForEnvUpdate,outputActionRequired,outputAgentError,quoteArg,redactEnvValueArgs,withGlobalFlags}from"../../chunks/chunk-RIDPB64C.js";import{getFlagsSpecification,getGlobalFlagsFromArgs}from"../../chunks/chunk-MI7W4QMV.js";import"../../chunks/chunk-4TTF5E5U.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import{printAlignedLabel}from"../../chunks/chunk-N7Q2IESO.js";import"../../chunks/chunk-WPQN5UKR.js";import{getTeamByIdOrSlug}from"../../chunks/chunk-2VBFQZ72.js";import{isAPIError}from"../../chunks/chunk-YIIPBH2D.js";import{getCommandName,getCommandNamePlain,require_lib}from"../../chunks/chunk-JESNVRVR.js";import{emoji,output_manager_default,prependEmoji}from"../../chunks/chunk-75IAMKGV.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);var import_constants=__toESM(require_dist2(),1);async function addEnvRecord(client,projectId,upsert,type,key,value,targets,gitBranch,visibility){let actionWord=upsert?"Overriding":"Adding";output_manager_default.debug(`${actionWord} ${type} Environment Variable ${key} to ${targets.length} targets`);let target=[],customEnvironmentIds=[];for(let t of targets)(import_constants.PROJECT_ENV_TARGET.includes(t)?target:customEnvironmentIds).push(t);let body={type,key,value,target,customEnvironmentIds:customEnvironmentIds.length>0?customEnvironmentIds:void 0,gitBranch:gitBranch||void 0,...visibility!==void 0?{visibility}:{}},args=upsert?`?upsert=${upsert}`:"",url=`/v10/projects/${projectId}/env${args}`;await client.fetch(url,{method:"POST",body})}var import_error_utils=__toESM(require_dist(),1),knownErrorsCodes=new Set(["BAD_REQUEST","ENV_ALREADY_EXISTS","ENV_CONFLICT","EXISTING_KEY_AND_TARGET","FORBIDDEN","ID_NOT_FOUND","INVALID_KEY","INVALID_VALUE","KEY_INVALID_CHARACTERS","KEY_INVALID_LENGTH","KEY_RESERVED","RESERVED_ENV_VARIABLE","MAX_ENVS_EXCEEDED","MISSING_ID","MISSING_KEY","MISSING_TARGET","MISSING_VALUE","NOT_AUTHORIZED","NOT_DECRYPTABLE","SYSTEM_ENV_WITH_VALUE","TEAM_NOT_FOUND","TOO_MANY_IDS","TOO_MANY_KEYS","UNKNOWN_ERROR","VALUE_INVALID_LENGTH","VALUE_INVALID_TYPE"]);function isKnownError(error){let code=(0,import_error_utils.isErrnoException)(error)?error.code:null;return code?knownErrorsCodes.has(code.toUpperCase()):!1}var EnvAddTelemetryClient=class extends TelemetryClient{trackCliArgumentName(name){name&&this.trackCliArgument({arg:"name",value:this.redactedValue})}trackCliArgumentEnvironment(environment){if(environment){let allStandard=environment.split(",").map(t=>t.trim()).every(t=>STANDARD_ENVIRONMENTS.includes(t));this.trackCliArgument({arg:"environment",value:allStandard?environment:this.redactedValue})}}trackCliArgumentGitBranch(gitBranch){gitBranch&&this.trackCliArgument({arg:"git-branch",value:this.redactedValue})}trackCliOptionGitBranch(gitBranch){gitBranch&&this.trackCliOption({option:"git-branch",value:this.redactedValue})}trackCliOptionValue(value){value&&this.trackCliOption({option:"value",value:this.redactedValue})}trackCliOptionVisibility(visibility){if(visibility){let validVisibilities=["config","secret"];this.trackCliOption({option:"visibility",value:validVisibilities.includes(visibility)?visibility:this.redactedValue})}}trackCliOptionType(type){if(type){let validTypes=["config","secret"];this.trackCliOption({option:"type",value:validTypes.includes(type)?type:this.redactedValue})}}trackCliFlagSensitive(sensitive){sensitive&&this.trackCliFlag("sensitive")}trackCliFlagNoSensitive(noSensitive){noSensitive&&this.trackCliFlag("no-sensitive")}trackCliFlagForce(force){force&&this.trackCliFlag("force")}trackCliFlagGuidance(guidance){guidance&&this.trackCliFlag("guidance")}trackCliFlagYes(yes){yes&&this.trackCliFlag("yes")}};import{determineAgent}from"@vercel/detect-agent";function includesDevelopment(targets){return targets.length===0||targets.includes("development")}function getProductionSecretPolicyErrorKind(message){return/production secrets?.*different value|different value.*production secrets?/i.test(message)?"different-values":/production secrets?.*(?:own environment group|separat)|(?:own environment group|separat).*production secrets?/i.test(message)?"separate-environments":null}function getProductionSecretPolicyRecovery(kind){return kind==="different-values"?"Use different Secret values for Production and non-Production.":"Create separate Production and non-Production variables with different values."}function getSecretStorageChoice(targets,recommendedReason){let availability=includesDevelopment(targets)?"hidden in the dashboard; Development values can be pulled":"hidden in the dashboard and unavailable to pulls",recommendation=recommendedReason?`; recommended ${recommendedReason}`:"";return`Secret (${availability}${recommendation})`}function getDefaultSecretStorageGuidance(targets){return includesDevelopment(targets)?"Stored as Secret by default. This value is hidden in the dashboard; Development values can be pulled. Use `--type config` for other values you need to read later.":"Stored as Secret by default. This value is hidden in the dashboard and unavailable to pulls; use `--type config` for values you need to read later."}function looksLikeCredentialName(key,publicPrefix=getPublicPrefix(key)){return looksLikeSecret(publicPrefix?key.slice(publicPrefix.length):key)}function filterEnvChoicesForSensitivity(choices,opts){return opts.policyOn?choices.filter(c=>c.value==="development"):choices}function getTargetCompatibilityError(envTargets,isSensitive,policyOn){let hasSensitiveCapable=envTargets.some(t=>t!=="development");return!isSensitive&&policyOn&&hasSensitiveCapable?`Your team requires sensitive Environment Variables for Production and Preview. To add a non-sensitive value, target the Development Environment only. Run ${getCommandName("env add")} with the development target instead.`:null}function resolveFinalType(envTargets,isSensitive,opts){return envTargets.includes("development")&&!isSensitive||opts.forceEncrypted&&!opts.policyOn?"encrypted":isSensitive||opts.forceSensitive||opts.policyOn?"sensitive":"encrypted"}function fillEnvAddTemplate(template,opts){let targetPlaceholder=getEnvTargetPlaceholder();return template.replace(/<name>/g,opts.envName?quoteArg(opts.envName):"<name>").split(targetPlaceholder).join(opts.envTargetArg?quoteArg(opts.envTargetArg):targetPlaceholder).replace(/<git-branch>/g,opts.envGitBranch?quoteArg(opts.envGitBranch):"<git-branch>").replace(/<gitbranch>/g,opts.envGitBranch?quoteArg(opts.envGitBranch):"<gitbranch>").replace(/<value>/g,"<value>")}function multiTargetSuggestion(argv,envName,targets,addNoSensitive){let flag=addNoSensitive?" --no-sensitive":"";return{command:buildEnvAddCommandWithPreservedArgs(argv,`env add ${envName} ${targets.join(",")} --value "<value>"${flag} --yes`),when:addNoSensitive?"Add one non-sensitive variable to all listed environments":"Add one variable to multiple environments"}}function filterSensitiveMultiTargetSuggestionTargets(targets,_opts){return targets}function projectLabel(link){return`${link.org.slug}/${link.project.name}`}function formatEnvironmentTarget(target,customEnvironments){let standardTarget=envTargetChoices.find(choice=>choice.value===target);return standardTarget?standardTarget.name:customEnvironments.find(env=>env.id===target||env.slug===target)?.slug??target}function formatEnvironmentTargets(envTargets,customEnvironments){return envTargets.map(target=>formatEnvironmentTarget(target,customEnvironments)).join(", ")}function printEnvAddResult(link,envName,envTargets,envGitBranch,customEnvironments,finalType,force,visibility){output_manager_default.print(`
7
+ import{CHECKBOX_INSTRUCTIONS,getCustomEnvironments,readStandardInput,require_dist as require_dist3}from"../../chunks/chunk-6JGC4YDH.js";import{getInvalidSubcommand}from"../../chunks/chunk-TG2RCYTH.js";import{ellipsis}from"../../chunks/chunk-F4KY2TOK.js";import{formatTable}from"../../chunks/chunk-LSQREJXO.js";import"../../chunks/chunk-ID663OJ7.js";import{autoInstallVercelPlugin}from"../../chunks/chunk-ZZ3LJ22B.js";import{require_execa}from"../../chunks/chunk-KKCBFBJK.js";import{ENV_VISIBILITY_DEPRECATION_MESSAGE,SENSITIVE_ENV_VALUE_PLACEHOLDER,formatVisibilityLabel,getApiPublicPrefix,getEnvKeyWarnings,getFrameworkPublicPrefix,getLocalSecretFallbackMessage,getLocalSvelteKitPublicPrefixes,getPublicPrefix,getPublicPrefixSecretVisibilityError,getUnavailableSecretValuesMessage,isFlagsSecretNeedingSplit,isSecretEnvVar,looksLikeSecret,looksLikeSecretValue,normalizeStdinEnvValue,pull,removePublicPrefix,resolveEnvVarTypeOption,resolveEnvVarVisibility,shouldConfirmRotationBeforeDelete,validateEnvValue}from"../../chunks/chunk-XJXX4QXA.js";import{resolveProjectContext}from"../../chunks/chunk-6ZRULOO3.js";import"../../chunks/chunk-25565AGS.js";import{isGuidanceEnabled,suggestNextCommands}from"../../chunks/chunk-YROIQRYI.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-J24BABG4.js";import{getEnvRecords,pullEnvRecords}from"../../chunks/chunk-YS542RHZ.js";import"../../chunks/chunk-GCSAJUL6.js";import"../../chunks/chunk-E6R2QOOR.js";import"../../chunks/chunk-PVASGBEF.js";import"../../chunks/chunk-MVCAUS4F.js";import{getCommandAliases}from"../../chunks/chunk-NLCTF4EJ.js";import"../../chunks/chunk-ZBDLYNUF.js";import"../../chunks/chunk-J6O6JW2K.js";import"../../chunks/chunk-BFRDBBSO.js";import"../../chunks/chunk-2UMWTCY7.js";import"../../chunks/chunk-Q5ZGA2RO.js";import"../../chunks/chunk-UGMTKOTN.js";import"../../chunks/chunk-UQIVF4Q2.js";import"../../chunks/chunk-ITKS32PG.js";import"../../chunks/chunk-7NNENHGN.js";import"../../chunks/chunk-Y24OSBXP.js";import"../../chunks/chunk-GVVIFYQE.js";import"../../chunks/chunk-W3TGCMRW.js";import"../../chunks/chunk-B4YYOSPY.js";import"../../chunks/chunk-LD5U73LA.js";import"../../chunks/chunk-VRWLNWNE.js";import"../../chunks/chunk-TPVAPVQC.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-FBYA6LLM.js";import{addSubcommand,envCommand,envTargetChoices,getEnvTargetPlaceholder,isValidEnvTarget,listSubcommand,parseEnvTargetArg,pullSubcommand,removeSubcommand,runSubcommand,updateSubcommand}from"../../chunks/chunk-CMKLX4DC.js";import"../../chunks/chunk-EVQJ7SCV.js";import"../../chunks/chunk-SCV7XEEO.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import{formatEnvironment}from"../../chunks/chunk-CYV3X62I.js";import{validateLsArgs}from"../../chunks/chunk-DNDBPLLI.js";import{STANDARD_ENVIRONMENTS,formatProject}from"../../chunks/chunk-WYI4VNXT.js";import"../../chunks/chunk-Q7D7RGXM.js";import{parseTarget}from"../../chunks/chunk-2B3A3MOX.js";import"../../chunks/chunk-IVIZLWZQ.js";import"../../chunks/chunk-HVUJNVPS.js";import"../../chunks/chunk-UCAE5Z5L.js";import{help}from"../../chunks/chunk-H3KYG32S.js";import"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-QAETJRKX.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{validateJsonOutput}from"../../chunks/chunk-D4MW3RDW.js";import"../../chunks/chunk-IIC2A4YN.js";import{TelemetryClient,require_dist as require_dist2}from"../../chunks/chunk-KUGXOLL7.js";import"../../chunks/chunk-MV4WHUIC.js";import"../../chunks/chunk-VKXEOL4K.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import"../../chunks/chunk-NWGBDBZI.js";import"../../chunks/chunk-4SAVH3H7.js";import"../../chunks/chunk-ZS2WS4AM.js";import"../../chunks/chunk-AOWWC6WZ.js";import"../../chunks/chunk-MY4MONOH.js";import{parseArguments}from"../../chunks/chunk-ELDHGU6N.js";import{buildCommandWithYes,buildEnvAddCommandWithPreservedArgs,buildEnvRmCommandWithPreservedArgs,buildEnvUpdateCommandWithPreservedArgs,getPreservedArgsForEnvAdd,getPreservedArgsForEnvRm,getPreservedArgsForEnvUpdate,outputActionRequired,outputAgentError,quoteArg,redactEnvValueArgs,withGlobalFlags}from"../../chunks/chunk-BAT6SDBJ.js";import{getFlagsSpecification,getGlobalFlagsFromArgs}from"../../chunks/chunk-MI7W4QMV.js";import"../../chunks/chunk-U3NQZJQ4.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import{printAlignedLabel}from"../../chunks/chunk-IJCCFLCQ.js";import"../../chunks/chunk-ZQME5XUJ.js";import{getTeamByIdOrSlug}from"../../chunks/chunk-2VBFQZ72.js";import{isAPIError}from"../../chunks/chunk-XSDAUM4F.js";import{getCommandName,getCommandNamePlain,require_lib}from"../../chunks/chunk-JESNVRVR.js";import{emoji,output_manager_default,prependEmoji}from"../../chunks/chunk-M774HRX5.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);var import_constants=__toESM(require_dist2(),1);async function addEnvRecord(client,projectId,upsert,type,key,value,targets,gitBranch,visibility){let actionWord=upsert?"Overriding":"Adding";output_manager_default.debug(`${actionWord} ${type} Environment Variable ${key} to ${targets.length} targets`);let target=[],customEnvironmentIds=[];for(let t of targets)(import_constants.PROJECT_ENV_TARGET.includes(t)?target:customEnvironmentIds).push(t);let body={type,key,value,target,customEnvironmentIds:customEnvironmentIds.length>0?customEnvironmentIds:void 0,gitBranch:gitBranch||void 0,...visibility!==void 0?{visibility}:{}},args=upsert?`?upsert=${upsert}`:"",url=`/v10/projects/${projectId}/env${args}`;await client.fetch(url,{method:"POST",body})}var import_error_utils=__toESM(require_dist(),1),knownErrorsCodes=new Set(["BAD_REQUEST","ENV_ALREADY_EXISTS","ENV_CONFLICT","EXISTING_KEY_AND_TARGET","FORBIDDEN","ID_NOT_FOUND","INVALID_KEY","INVALID_VALUE","KEY_INVALID_CHARACTERS","KEY_INVALID_LENGTH","KEY_RESERVED","RESERVED_ENV_VARIABLE","MAX_ENVS_EXCEEDED","MISSING_ID","MISSING_KEY","MISSING_TARGET","MISSING_VALUE","NOT_AUTHORIZED","NOT_DECRYPTABLE","SYSTEM_ENV_WITH_VALUE","TEAM_NOT_FOUND","TOO_MANY_IDS","TOO_MANY_KEYS","UNKNOWN_ERROR","VALUE_INVALID_LENGTH","VALUE_INVALID_TYPE"]);function isKnownError(error){let code=(0,import_error_utils.isErrnoException)(error)?error.code:null;return code?knownErrorsCodes.has(code.toUpperCase()):!1}var EnvAddTelemetryClient=class extends TelemetryClient{trackCliArgumentName(name){name&&this.trackCliArgument({arg:"name",value:this.redactedValue})}trackCliArgumentEnvironment(environment){if(environment){let allStandard=environment.split(",").map(t=>t.trim()).every(t=>STANDARD_ENVIRONMENTS.includes(t));this.trackCliArgument({arg:"environment",value:allStandard?environment:this.redactedValue})}}trackCliArgumentGitBranch(gitBranch){gitBranch&&this.trackCliArgument({arg:"git-branch",value:this.redactedValue})}trackCliOptionGitBranch(gitBranch){gitBranch&&this.trackCliOption({option:"git-branch",value:this.redactedValue})}trackCliOptionValue(value){value&&this.trackCliOption({option:"value",value:this.redactedValue})}trackCliOptionVisibility(visibility){if(visibility){let validVisibilities=["config","secret"];this.trackCliOption({option:"visibility",value:validVisibilities.includes(visibility)?visibility:this.redactedValue})}}trackCliOptionType(type){if(type){let validTypes=["config","secret"];this.trackCliOption({option:"type",value:validTypes.includes(type)?type:this.redactedValue})}}trackCliFlagSensitive(sensitive){sensitive&&this.trackCliFlag("sensitive")}trackCliFlagNoSensitive(noSensitive){noSensitive&&this.trackCliFlag("no-sensitive")}trackCliFlagForce(force){force&&this.trackCliFlag("force")}trackCliFlagGuidance(guidance){guidance&&this.trackCliFlag("guidance")}trackCliFlagYes(yes){yes&&this.trackCliFlag("yes")}};import{determineAgent}from"@vercel/detect-agent";function includesDevelopment(targets){return targets.length===0||targets.includes("development")}function getProductionSecretPolicyErrorKind(message){return/production secrets?.*different value|different value.*production secrets?/i.test(message)?"different-values":/production secrets?.*(?:own environment group|separat)|(?:own environment group|separat).*production secrets?/i.test(message)?"separate-environments":null}function getProductionSecretPolicyRecovery(kind){return kind==="different-values"?"Use different Secret values for Production and non-Production.":"Create separate Production and non-Production variables with different values."}function getSecretStorageChoice(targets,recommendedReason){let availability=includesDevelopment(targets)?"hidden in the dashboard; Development values can be pulled":"hidden in the dashboard and unavailable to pulls",recommendation=recommendedReason?`; recommended ${recommendedReason}`:"";return`Secret (${availability}${recommendation})`}function getDefaultSecretStorageGuidance(targets){return includesDevelopment(targets)?"Stored as Secret by default. This value is hidden in the dashboard; Development values can be pulled. Use `--type config` for other values you need to read later.":"Stored as Secret by default. This value is hidden in the dashboard and unavailable to pulls; use `--type config` for values you need to read later."}function looksLikeCredentialName(key,publicPrefix=getPublicPrefix(key)){return looksLikeSecret(publicPrefix?key.slice(publicPrefix.length):key)}function filterEnvChoicesForSensitivity(choices,opts){return opts.policyOn?choices.filter(c=>c.value==="development"):choices}function getTargetCompatibilityError(envTargets,isSensitive,policyOn){let hasSensitiveCapable=envTargets.some(t=>t!=="development");return!isSensitive&&policyOn&&hasSensitiveCapable?`Your team requires sensitive Environment Variables for Production and Preview. To add a non-sensitive value, target the Development Environment only. Run ${getCommandName("env add")} with the development target instead.`:null}function resolveFinalType(envTargets,isSensitive,opts){return envTargets.includes("development")&&!isSensitive||opts.forceEncrypted&&!opts.policyOn?"encrypted":isSensitive||opts.forceSensitive||opts.policyOn?"sensitive":"encrypted"}function fillEnvAddTemplate(template,opts){let targetPlaceholder=getEnvTargetPlaceholder();return template.replace(/<name>/g,opts.envName?quoteArg(opts.envName):"<name>").split(targetPlaceholder).join(opts.envTargetArg?quoteArg(opts.envTargetArg):targetPlaceholder).replace(/<git-branch>/g,opts.envGitBranch?quoteArg(opts.envGitBranch):"<git-branch>").replace(/<gitbranch>/g,opts.envGitBranch?quoteArg(opts.envGitBranch):"<gitbranch>").replace(/<value>/g,"<value>")}function multiTargetSuggestion(argv,envName,targets,addNoSensitive){let flag=addNoSensitive?" --no-sensitive":"";return{command:buildEnvAddCommandWithPreservedArgs(argv,`env add ${envName} ${targets.join(",")} --value "<value>"${flag} --yes`),when:addNoSensitive?"Add one non-sensitive variable to all listed environments":"Add one variable to multiple environments"}}function filterSensitiveMultiTargetSuggestionTargets(targets,_opts){return targets}function projectLabel(link){return`${link.org.slug}/${link.project.name}`}function formatEnvironmentTarget(target,customEnvironments){let standardTarget=envTargetChoices.find(choice=>choice.value===target);return standardTarget?standardTarget.name:customEnvironments.find(env=>env.id===target||env.slug===target)?.slug??target}function formatEnvironmentTargets(envTargets,customEnvironments){return envTargets.map(target=>formatEnvironmentTarget(target,customEnvironments)).join(", ")}function printEnvAddResult(link,envName,envTargets,envGitBranch,customEnvironments,finalType,force,visibility){output_manager_default.print(`
8
8
  `),printAlignedLabel(force?"Overrode":"Added",envName,{gutter:"\u2713"}),printAlignedLabel("Project",projectLabel(link)),printAlignedLabel("Environments",formatEnvironmentTargets(envTargets,customEnvironments)),envGitBranch&&printAlignedLabel("Branch",envGitBranch);let visibilityLabel=formatVisibilityLabel(visibility,finalType);visibilityLabel&&printAlignedLabel("Type",visibilityLabel)}function printEnvAddWarning(message){output_manager_default.print(`${import_chalk.default.yellow("!")} ${message}
9
9
  `)}function promptEnvValue(client,opts){return client.input.text({message:"Value?",...opts.isSensitive?{transformer:value=>"*".repeat(value.length)}:{}})}function buildHumanEnvAddCommand(argv,commandTemplate){let globalFlags=getGlobalFlagsFromArgs(argv.slice(2),{preserveProject:!0}).filter(flag=>!flag.startsWith("--non-interactive")),suffix=globalFlags.length>0?` ${globalFlags.map(quoteArg).join(" ")}`:"";return getCommandNamePlain(`${commandTemplate}${suffix}`)}async function add(client,argv){let parsedArgs,flagsSpecification=getFlagsSpecification(addSubcommand.options);try{parsedArgs=parseArguments(argv,flagsSpecification)}catch(err){return client.nonInteractive&&outputAgentError(client,{status:"error",reason:"invalid_arguments",message:err instanceof Error?err.message:String(err)},2),printError(err),2}let{args,flags:opts}=parsedArgs,stdInput=await readStandardInput(client.stdin),valueFromFlag=typeof opts["--value"]=="string"?opts["--value"]:void 0,[envName,envTargetArg]=args,positionalGitBranch=args[2],optionGitBranch=typeof opts["--git-branch"]=="string"?opts["--git-branch"]:void 0,envGitBranch=optionGitBranch??positionalGitBranch,forceSensitive=!!opts["--sensitive"],forceEncrypted=!!opts["--no-sensitive"],typeOption=resolveEnvVarTypeOption({type:typeof opts["--type"]=="string"?opts["--type"]:void 0,visibility:typeof opts["--visibility"]=="string"?opts["--visibility"]:void 0}),explicitType=typeOption.explicitVisibility,typeSource=explicitType||forceSensitive||forceEncrypted?"argv":void 0,telemetryClient=new EnvAddTelemetryClient({opts:{store:client.telemetryEventStore}});if(telemetryClient.trackCliArgumentName(envName),telemetryClient.trackCliArgumentEnvironment(envTargetArg),telemetryClient.trackCliArgumentGitBranch(positionalGitBranch),telemetryClient.trackCliOptionGitBranch(optionGitBranch),telemetryClient.trackCliOptionValue(valueFromFlag===void 0?void 0:"<redacted>"),telemetryClient.trackCliFlagSensitive(opts["--sensitive"]),telemetryClient.trackCliFlagNoSensitive(opts["--no-sensitive"]),telemetryClient.trackCliFlagForce(opts["--force"]),telemetryClient.trackCliFlagGuidance(opts["--guidance"]),telemetryClient.trackCliFlagYes(opts["--yes"]),telemetryClient.trackCliOptionType(typeof opts["--type"]=="string"?opts["--type"]:void 0),telemetryClient.trackCliOptionVisibility(typeof opts["--visibility"]=="string"?opts["--visibility"]:void 0),telemetryClient.trackCliOptionProject(opts["--project"]),typeOption.error)return client.nonInteractive&&outputAgentError(client,{status:"error",reason:typeOption.errorReason??"invalid_type",message:typeOption.error},1),output_manager_default.fatal(typeOption.error),1;typeOption.usedDeprecatedVisibility&&printEnvAddWarning(ENV_VISIBILITY_DEPRECATION_MESSAGE);let typeConflictMessage=forceSensitive?forceEncrypted?"`--sensitive` and `--no-sensitive` cannot be used together. Pick one.":explicitType==="config"?"`--type config` cannot be used with `--sensitive`. Pick one.":null:forceEncrypted&&explicitType==="secret"?"`--type secret` cannot be used with `--no-sensitive`. Pick one.":null;if(typeConflictMessage)return client.nonInteractive&&outputAgentError(client,{status:"error",reason:"conflicting_type_flags",message:typeConflictMessage},2),output_manager_default.fatal(typeConflictMessage),2;if(positionalGitBranch&&optionGitBranch)return output_manager_default.error("Git branch was provided twice. Use either `--git-branch <git-branch>` or the legacy third argument."),2;if(args.length>3)return output_manager_default.error(`Invalid number of arguments. Usage: ${getCommandName(`env add <name> ${getEnvTargetPlaceholder()} --git-branch <git-branch>`)}`),2;if(stdInput&&(!envName||!envTargetArg))return output_manager_default.error(`Invalid number of arguments. Usage: ${getCommandName("env add <name> <target> --git-branch <git-branch> < <file>")}`),2;let envTargets=envTargetArg?parseEnvTargetArg(envTargetArg):[],resolvedLink;if(client.nonInteractive){let link2=await resolveProjectContext({client,projectNameOrId:opts["--project"]});if(link2.status==="error")return link2.exitCode;if(link2.status==="not_linked"){let preserved=getPreservedArgsForEnvAdd(client.argv),linkPreserved=preserved.filter((a,i)=>!(a==="--value"||a.startsWith("--value=")||i>0&&preserved[i-1]==="--value")),linkArgv=[...client.argv.slice(0,2),"link","--scope","<scope>",...linkPreserved],envAddRetryArgv=redactEnvValueArgs(client.argv);if(envTargetArg==="preview"&&envGitBranch===void 0){let argvArgs=client.argv.slice(2),addIdx=argvArgs.indexOf("add");if(addIdx!==-1){let pos=addIdx+1,positionals=0;for(;pos<argvArgs.length&&positionals<3&&!argvArgs[pos].startsWith("-");)positionals++,pos++;let insertAt=2+pos;envAddRetryArgv=redactEnvValueArgs([...client.argv.slice(0,insertAt),"<gitbranch>",...client.argv.slice(insertAt)])}}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 mode; use \`--scope\` or \`--project\` to specify a team or project. Then run your \`env add\` command.`,next:[{command:buildCommandWithYes(linkArgv)},{command:buildCommandWithYes(envAddRetryArgv)}]},1)}if(link2.status!=="linked")return 1;resolvedLink=link2;let{project:project2}=link2,org=link2.org;client.config.currentTeam=org.type==="team"?org.id:void 0;let[{envs:envs2},customEnvironments2]=await Promise.all([getEnvRecords(client,project2.id,"vercel-cli:env:add"),getCustomEnvironments(client,project2.id)]),matchingEnvs2=envs2.filter(r=>r.key===envName),existingTargets2=new Set,existingCustomEnvs2=new Set;for(let env of matchingEnvs2){if(typeof env.target=="string")existingTargets2.add(env.target);else if(Array.isArray(env.target))for(let target of env.target)existingTargets2.add(target);if(env.customEnvironmentIds)for(let customEnvId of env.customEnvironmentIds)existingCustomEnvs2.add(customEnvId)}let choices2=[...envTargetChoices.filter(c=>!existingTargets2.has(c.value)),...customEnvironments2.filter(c=>!existingCustomEnvs2.has(c.id)).map(c=>({name:c.slug,value:c.id}))],missing=[];if(envName||missing.push("missing_name"),valueFromFlag===void 0&&!stdInput&&missing.push("missing_value"),!envTargetArg&&choices2.length>0&&missing.push("missing_environment"),envTargetArg==="preview"&&envGitBranch===void 0&&!(client.nonInteractive&&args.length===2)&&missing.push("git_branch_required"),missing.length>0){let parts=missing.map(m=>m==="missing_name"?"variable name":m==="missing_value"?"--value or stdin":m==="missing_environment"?"environment (production, preview, development, or a comma-separated list)":m==="git_branch_required"?"`--git-branch <git-branch>` for Preview, or omit for all Preview branches":m),fullTemplate=`env add <name> ${getEnvTargetPlaceholder()} --value "<value>" --yes`,filledTemplate=fillEnvAddTemplate(fullTemplate,{envName,envTargetArg,envGitBranch}),next=[];if(missing.length===1&&missing[0]==="git_branch_required"||next.push({command:buildEnvAddCommandWithPreservedArgs(client.argv,filledTemplate)}),missing.includes("git_branch_required")&&envName&&(valueFromFlag!==void 0||stdInput)){let branchSpecific=fillEnvAddTemplate('env add <name> preview --git-branch <git-branch> --value "<value>" --yes',{envName,envTargetArg:"preview"}),branchAll=fillEnvAddTemplate('env add <name> preview --value "<value>" --yes',{envName,envTargetArg:"preview"});next.push({command:buildEnvAddCommandWithPreservedArgs(client.argv,branchSpecific),when:"Add to a specific Git branch"},{command:buildEnvAddCommandWithPreservedArgs(client.argv,branchAll),when:"Add to all Preview branches"})}if(missing.includes("missing_environment")){let standardAvailable=choices2.map(c=>c.value).filter(v=>isValidEnvTarget(v)),multiTargets=filterSensitiveMultiTargetSuggestionTargets(standardAvailable,{forceSensitive:!!opts["--sensitive"],policyOn:!1});multiTargets.length>1&&next.push(multiTargetSuggestion(client.argv,envName||"<name>",multiTargets,multiTargets.includes("development")&&!opts["--no-sensitive"]))}outputActionRequired(client,{status:"action_required",reason:"missing_requirements",missing,message:`Provide all required inputs for non-interactive mode: ${parts.join("; ")}. Example: \`${filledTemplate}\``,next},1)}}if(envName||(envName=await client.input.text({message:"Name?",validate:val=>val?!0:"Name cannot be empty"})),!resolvedLink){let link2=await resolveProjectContext({client,projectNameOrId:opts["--project"]});if(link2.status==="error")return link2.exitCode;if(link2.status==="not_linked"){if(client.nonInteractive){let preserved=getPreservedArgsForEnvAdd(client.argv),linkPreserved=preserved.filter((a,i)=>!(a==="--value"||a.startsWith("--value=")||i>0&&preserved[i-1]==="--value")),linkArgv=[...client.argv.slice(0,2),"link","--scope","<scope>",...linkPreserved];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. Then run your env add command.`,next:[{command:buildCommandWithYes(linkArgv)},{command:buildCommandWithYes(redactEnvValueArgs(client.argv))}]},1)}else output_manager_default.error(`Your codebase isn\u2019t linked to a project on Vercel. Run ${getCommandName("link")} to begin.`);return 1}resolvedLink=link2}let link=resolvedLink;client.config.currentTeam=link.org.type==="team"?link.org.id:void 0;let{project}=link;if(explicitType==="secret"||forceSensitive){let publicPrefixError=getPublicPrefixSecretVisibilityError(envName,{visibility:explicitType==="secret"?"secret":void 0,type:"sensitive",context:"add"});if(publicPrefixError)return client.nonInteractive&&outputAgentError(client,{status:"error",reason:"invalid_type",message:publicPrefixError},2),output_manager_default.fatal(publicPrefixError),2}let keyAccepted=!1;for(;!keyAccepted;){let apiPublicPrefix2=getApiPublicPrefix(envName),frameworkPublicPrefix=getFrameworkPublicPrefix(project.framework,envName),globallyKnownPrefix=getPublicPrefix(envName),keyWarnings=frameworkPublicPrefix!==null&&(explicitType==="secret"||forceSensitive)||globallyKnownPrefix!==null&&apiPublicPrefix2===null&&frameworkPublicPrefix===null?[]:getEnvKeyWarnings(envName);if(!keyWarnings.find(w=>w.requiresConfirmation)){for(let warning of keyWarnings)printEnvAddWarning(warning.message);keyAccepted=!0;break}let nameWithoutPrefix=removePublicPrefix(envName),publicPrefix=getPublicPrefix(envName);if(typeSource==="argv"){for(let warning of keyWarnings)printEnvAddWarning(warning.message);keyAccepted=!0;break}let privateCommand=buildEnvAddCommandWithPreservedArgs(client.argv,`env add ${nameWithoutPrefix} ${envTargetArg??getEnvTargetPlaceholder()} --type secret --value "<value>" --yes`),publicCommand=buildEnvAddCommandWithPreservedArgs(client.argv,`env add ${envName} ${envTargetArg??getEnvTargetPlaceholder()} --type config --value "<value>" --yes`),humanTargetArg=envTargetArg?` ${envTargetArg}`:"",privateHumanCommand=buildHumanEnvAddCommand(client.argv,`env add ${nameWithoutPrefix}${humanTargetArg} --type secret`),publicHumanCommand=buildHumanEnvAddCommand(client.argv,`env add ${envName}${humanTargetArg} --type config`),message=`\`${envName}\` looks like a credential, and \`${publicPrefix}\` exposes its value to anyone visiting your site. Choose explicitly: rename to \`${nameWithoutPrefix}\` with \`--type secret\` to keep it private, or keep the name with \`--type config\` to expose it.`;if(client.nonInteractive||opts["--yes"]||stdInput)return client.nonInteractive&&outputActionRequired(client,{status:"action_required",reason:"public_prefix_requires_type",message,choices:[{id:"private",name:`Keep private: rename to ${nameWithoutPrefix} and use Secret`},{id:"public",name:`Expose publicly: keep ${envName} as Config`}],next:[{command:privateCommand,when:"Keep it private; replace <value> before running"},{command:publicCommand,when:"Expose it publicly; replace <value> before running"}]}),output_manager_default.fatal(message),output_manager_default.print(` Keep it private:
10
10
  ${privateHumanCommand}
@@ -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{promptExperimentalServicesMigration}from"../../chunks/chunk-WVJYKHGZ.js";import"../../chunks/chunk-YBOS65VB.js";import"../../chunks/chunk-BLAIBYEU.js";import"../../chunks/chunk-SQB4T5FL.js";import"../../chunks/chunk-7EJQLVWX.js";import{isPromptCanceledError}from"../../chunks/chunk-P2O5DOYE.js";import{pull}from"../../chunks/chunk-SRAC7DI4.js";import"../../chunks/chunk-EKUHN42H.js";import"../../chunks/chunk-25565AGS.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-J24BABG4.js";import{ensureLink}from"../../chunks/chunk-YP46QVEI.js";import"../../chunks/chunk-5JEU6QSM.js";import"../../chunks/chunk-3GSGG4YR.js";import"../../chunks/chunk-PVASGBEF.js";import"../../chunks/chunk-MVCAUS4F.js";import{addSubcommand8 as addSubcommand,getCommandAliases,linkCommand}from"../../chunks/chunk-EEZLBOSP.js";import"../../chunks/chunk-ZBDLYNUF.js";import"../../chunks/chunk-J6O6JW2K.js";import"../../chunks/chunk-2FHICLHJ.js";import"../../chunks/chunk-2UMWTCY7.js";import"../../chunks/chunk-Q5ZGA2RO.js";import"../../chunks/chunk-UGMTKOTN.js";import"../../chunks/chunk-BTCKMXWW.js";import"../../chunks/chunk-ITKS32PG.js";import"../../chunks/chunk-CN3IVZJO.js";import"../../chunks/chunk-Y24OSBXP.js";import"../../chunks/chunk-GVVIFYQE.js";import"../../chunks/chunk-W3TGCMRW.js";import"../../chunks/chunk-B4YYOSPY.js";import"../../chunks/chunk-LD5U73LA.js";import"../../chunks/chunk-X65QKYDM.js";import"../../chunks/chunk-TPVAPVQC.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-WE3ZJX7P.js";import"../../chunks/chunk-DYQXJCHO.js";import"../../chunks/chunk-SCV7XEEO.js";import"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-3EYOQC4R.js";import"../../chunks/chunk-XEQT373M.js";import"../../chunks/chunk-J2LAZELI.js";import"../../chunks/chunk-E6UKNYFF.js";import"../../chunks/chunk-UCAE5Z5L.js";import{help}from"../../chunks/chunk-4GL254L4.js";import"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-3EU7MN5M.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{detectExplicitScope,getScope}from"../../chunks/chunk-WZ7YJDKT.js";import{TelemetryClient}from"../../chunks/chunk-JNJOUMGF.js";import"../../chunks/chunk-PAN6TUTQ.js";import"../../chunks/chunk-VKXEOL4K.js";import"../../chunks/chunk-MXTC4ZAQ.js";import"../../chunks/chunk-NWGBDBZI.js";import"../../chunks/chunk-4SAVH3H7.js";import"../../chunks/chunk-ZS2WS4AM.js";import"../../chunks/chunk-AOWWC6WZ.js";import"../../chunks/chunk-MY4MONOH.js";import{parseArguments}from"../../chunks/chunk-CRQDQNQZ.js";import"../../chunks/chunk-RIDPB64C.js";import{getFlagsSpecification}from"../../chunks/chunk-MI7W4QMV.js";import{addRepoLink,ensureRepoLink,findRepoRoot,resolveProjectCwd}from"../../chunks/chunk-4TTF5E5U.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import"../../chunks/chunk-N7Q2IESO.js";import"../../chunks/chunk-WPQN5UKR.js";import"../../chunks/chunk-2VBFQZ72.js";import"../../chunks/chunk-YIIPBH2D.js";import{cmd}from"../../chunks/chunk-JESNVRVR.js";import{output_manager_default}from"../../chunks/chunk-75IAMKGV.js";import"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);import{join}from"path";var LinkTelemetryClient=class extends TelemetryClient{trackCliArgumentCwd(){this.trackCliArgument({arg:"cwd",value:this.redactedValue})}trackCliFlagRepo(flag){flag&&this.trackCliFlag("repo")}trackCliFlagYes(yes){yes&&this.trackCliFlag("yes")}trackCliFlagConfirm(flag){flag&&this.trackCliFlag("confirm")}trackCliOptionTeam(value){value&&this.trackCliOption({option:"team",value:this.redactedValue})}trackCliOptionProjectId(value){value&&this.trackCliOption({option:"project-id",value:this.redactedValue})}trackCliSubcommandAdd(actual){this.trackCliSubcommand({subcommand:"add",value:actual})}};var COMMAND_CONFIG={add:getCommandAliases(addSubcommand)};function warnOidcRefreshFailed(){output_manager_default.print(`${import_chalk.default.yellow("!")} Linked project, but failed to refresh VERCEL_OIDC_TOKEN in .env.local. Rerun the link command to retry.
7
+ import{promptExperimentalServicesMigration}from"../../chunks/chunk-KKQL4AKH.js";import"../../chunks/chunk-QC5AMRWR.js";import"../../chunks/chunk-BLAIBYEU.js";import"../../chunks/chunk-OCOVCC5Q.js";import"../../chunks/chunk-7EJQLVWX.js";import{isPromptCanceledError}from"../../chunks/chunk-P2O5DOYE.js";import{pull}from"../../chunks/chunk-XJXX4QXA.js";import"../../chunks/chunk-6ZRULOO3.js";import"../../chunks/chunk-25565AGS.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-J24BABG4.js";import{ensureLink}from"../../chunks/chunk-YS542RHZ.js";import"../../chunks/chunk-GCSAJUL6.js";import"../../chunks/chunk-E6R2QOOR.js";import"../../chunks/chunk-PVASGBEF.js";import"../../chunks/chunk-MVCAUS4F.js";import{addSubcommand8 as addSubcommand,getCommandAliases,linkCommand}from"../../chunks/chunk-NLCTF4EJ.js";import"../../chunks/chunk-ZBDLYNUF.js";import"../../chunks/chunk-J6O6JW2K.js";import"../../chunks/chunk-BFRDBBSO.js";import"../../chunks/chunk-2UMWTCY7.js";import"../../chunks/chunk-Q5ZGA2RO.js";import"../../chunks/chunk-UGMTKOTN.js";import"../../chunks/chunk-UQIVF4Q2.js";import"../../chunks/chunk-ITKS32PG.js";import"../../chunks/chunk-7NNENHGN.js";import"../../chunks/chunk-Y24OSBXP.js";import"../../chunks/chunk-GVVIFYQE.js";import"../../chunks/chunk-W3TGCMRW.js";import"../../chunks/chunk-B4YYOSPY.js";import"../../chunks/chunk-LD5U73LA.js";import"../../chunks/chunk-VRWLNWNE.js";import"../../chunks/chunk-TPVAPVQC.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-CMKLX4DC.js";import"../../chunks/chunk-EVQJ7SCV.js";import"../../chunks/chunk-SCV7XEEO.js";import"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-WYI4VNXT.js";import"../../chunks/chunk-2B3A3MOX.js";import"../../chunks/chunk-IVIZLWZQ.js";import"../../chunks/chunk-HVUJNVPS.js";import"../../chunks/chunk-UCAE5Z5L.js";import{help}from"../../chunks/chunk-H3KYG32S.js";import"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-QAETJRKX.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{detectExplicitScope,getScope}from"../../chunks/chunk-IIC2A4YN.js";import{TelemetryClient}from"../../chunks/chunk-KUGXOLL7.js";import"../../chunks/chunk-MV4WHUIC.js";import"../../chunks/chunk-VKXEOL4K.js";import"../../chunks/chunk-MXTC4ZAQ.js";import"../../chunks/chunk-NWGBDBZI.js";import"../../chunks/chunk-4SAVH3H7.js";import"../../chunks/chunk-ZS2WS4AM.js";import"../../chunks/chunk-AOWWC6WZ.js";import"../../chunks/chunk-MY4MONOH.js";import{parseArguments}from"../../chunks/chunk-ELDHGU6N.js";import"../../chunks/chunk-BAT6SDBJ.js";import{getFlagsSpecification}from"../../chunks/chunk-MI7W4QMV.js";import{addRepoLink,ensureRepoLink,findRepoRoot,resolveProjectCwd}from"../../chunks/chunk-U3NQZJQ4.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import"../../chunks/chunk-IJCCFLCQ.js";import"../../chunks/chunk-ZQME5XUJ.js";import"../../chunks/chunk-2VBFQZ72.js";import"../../chunks/chunk-XSDAUM4F.js";import{cmd}from"../../chunks/chunk-JESNVRVR.js";import{output_manager_default}from"../../chunks/chunk-M774HRX5.js";import"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);import{join}from"path";var LinkTelemetryClient=class extends TelemetryClient{trackCliArgumentCwd(){this.trackCliArgument({arg:"cwd",value:this.redactedValue})}trackCliFlagRepo(flag){flag&&this.trackCliFlag("repo")}trackCliFlagYes(yes){yes&&this.trackCliFlag("yes")}trackCliFlagConfirm(flag){flag&&this.trackCliFlag("confirm")}trackCliOptionTeam(value){value&&this.trackCliOption({option:"team",value:this.redactedValue})}trackCliOptionProjectId(value){value&&this.trackCliOption({option:"project-id",value:this.redactedValue})}trackCliSubcommandAdd(actual){this.trackCliSubcommand({subcommand:"add",value:actual})}};var COMMAND_CONFIG={add:getCommandAliases(addSubcommand)};function warnOidcRefreshFailed(){output_manager_default.print(`${import_chalk.default.yellow("!")} Linked project, but failed to refresh VERCEL_OIDC_TOKEN in .env.local. Rerun the link command to retry.
8
8
  `)}async function refreshOidcTokenAfterLink(client,cwd){let originalCwd=client.cwd;try{client.cwd=await resolveProjectCwd(cwd),output_manager_default.print(`
9
9
  `),await pull(client,["--yes"],"vercel-cli:link",{oidcTokenOnly:!0})!==0&&warnOidcRefreshFailed()}catch{warnOidcRefreshFailed()}finally{client.cwd=originalCwd}}async function link(client){try{return await client.withEscapePromptCancellation(()=>linkProject(client))}catch(error){if(isPromptCanceledError(error))return output_manager_default.print(` Canceled.
10
10
  `),0;throw error}}async function linkProject(client){let parsedArgs=null,flagsSpecification=getFlagsSpecification(linkCommand.options);try{parsedArgs=parseArguments(client.argv.slice(2),flagsSpecification,{permissive:!0})}catch(error){return printError(error),2}let{subcommand,subcommandOriginal}=getSubcommand(parsedArgs.args.slice(1),COMMAND_CONFIG),telemetry=new LinkTelemetryClient({opts:{store:client.telemetryEventStore}});function printHelp(command){output_manager_default.print(help(command,{parent:linkCommand,columns:client.stderr.columns}))}if(subcommand==="add"){if(parsedArgs.flags["--help"])return telemetry.trackCliFlagHelp("link",subcommandOriginal),printHelp(addSubcommand),0;telemetry.trackCliSubcommandAdd(subcommandOriginal);let yes2=!!parsedArgs.flags["--yes"];try{await addRepoLink(client,client.cwd,{yes:yes2})}catch(err){if(isPromptCanceledError(err))throw err;return output_manager_default.prettyError(err),1}return 0}try{parsedArgs=parseArguments(client.argv.slice(2),flagsSpecification)}catch(error){return printError(error),2}if(parsedArgs.flags["--help"])return telemetry.trackCliFlagHelp("link"),output_manager_default.print(help(linkCommand,{columns:client.stderr.columns})),0;telemetry.trackCliFlagRepo(parsedArgs.flags["--repo"]),telemetry.trackCliFlagYes(parsedArgs.flags["--yes"]),telemetry.trackCliOptionProject(parsedArgs.flags["--project"]),"--confirm"in parsedArgs.flags&&(telemetry.trackCliFlagConfirm(parsedArgs.flags["--confirm"]),output_manager_default.warn("`--confirm` is deprecated, please use `--yes` instead"),parsedArgs.flags["--yes"]=parsedArgs.flags["--confirm"]);let yes=!!parsedArgs.flags["--yes"],cwd=parsedArgs.args[1];if(cwd?(telemetry.trackCliArgumentCwd(),output_manager_default.warn(`The ${cmd("vc link <directory>")} syntax is deprecated, please use ${cmd(`vc link --cwd ${cwd}`)} instead`)):cwd=client.cwd,parsedArgs.flags["--repo"]){output_manager_default.warn(`The ${cmd("--repo")} flag is in alpha, please report issues`);try{await ensureRepoLink(client,cwd,{yes,overwrite:!0})}catch(err){if(isPromptCanceledError(err))throw err;return output_manager_default.prettyError(err),1}}else{let selectedOrg=detectExplicitScope(client)?(await getScope(client,{resolveLocalScope:!0})).org:void 0,linkNonInteractive=client.nonInteractive||client.argv.includes("--non-interactive"),link2=await ensureLink("link",client,cwd,{autoConfirm:yes,forceDelete:!0,selectedOrg,projectName:parsedArgs.flags["--project"],successEmoji:"success",nonInteractive:linkNonInteractive,pullEnv:!1});if(typeof link2=="number")return link2;let projectCwd=await resolveProjectCwd(cwd),rootDirectory=link2.project.rootDirectory,repoRoot=link2.repoRoot??(rootDirectory?await findRepoRoot(projectCwd):void 0);await promptExperimentalServicesMigration({client,cwd:rootDirectory?join(repoRoot??projectCwd,rootDirectory):link2.repoRoot??projectCwd,autoConfirm:yes,nonInteractive:linkNonInteractive,allowConfigExecution:!1}),await refreshOidcTokenAfterLink(client,cwd)}return 0}export{link as default};
@@ -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{getPaginationOpts,isValidName}from"../../chunks/chunk-ILFUNCJZ.js";import{getCommandFlags}from"../../chunks/chunk-OUHPDA7Q.js";import{parseMeta}from"../../chunks/chunk-CZSOZKHX.js";import{formatEnvironment}from"../../chunks/chunk-JSBEAHKA.js";import{validateLsArgs}from"../../chunks/chunk-EO7GUARB.js";import{formatProject}from"../../chunks/chunk-3EYOQC4R.js";import{elapsed}from"../../chunks/chunk-Q7D7RGXM.js";import{parseTarget}from"../../chunks/chunk-XEQT373M.js";import{getDeployment,toHost}from"../../chunks/chunk-J2LAZELI.js";import"../../chunks/chunk-E6UKNYFF.js";import{listCommand}from"../../chunks/chunk-UCAE5Z5L.js";import{help}from"../../chunks/chunk-4GL254L4.js";import{table}from"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-3EU7MN5M.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{validateJsonOutput}from"../../chunks/chunk-D4MW3RDW.js";import{getContextName}from"../../chunks/chunk-WZ7YJDKT.js";import{TelemetryClient}from"../../chunks/chunk-JNJOUMGF.js";import"../../chunks/chunk-PAN6TUTQ.js";import"../../chunks/chunk-VKXEOL4K.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import"../../chunks/chunk-NWGBDBZI.js";import"../../chunks/chunk-4SAVH3H7.js";import"../../chunks/chunk-ZS2WS4AM.js";import"../../chunks/chunk-AOWWC6WZ.js";import"../../chunks/chunk-MY4MONOH.js";import{parseArguments}from"../../chunks/chunk-CRQDQNQZ.js";import{exitWithNonInteractiveError}from"../../chunks/chunk-RIDPB64C.js";import{getFlagsSpecification}from"../../chunks/chunk-MI7W4QMV.js";import{getLinkedProject,getProjectByNameOrId}from"../../chunks/chunk-4TTF5E5U.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import"../../chunks/chunk-N7Q2IESO.js";import"../../chunks/chunk-WPQN5UKR.js";import"../../chunks/chunk-2VBFQZ72.js";import{ProjectNotFound}from"../../chunks/chunk-YIIPBH2D.js";import{getCommandName,require_lib}from"../../chunks/chunk-JESNVRVR.js";import{output_manager_default}from"../../chunks/chunk-75IAMKGV.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_ms=__toESM(require_ms(),1),import_chalk=__toESM(require_source(),1),import_title=__toESM(require_lib(),1);function parsePolicy(policy){if(!policy)return{};typeof policy=="string"&&(policy=[policy]);let parsed={};for(let item of policy){let[key,...rest]=item.split("=");parsed[key]=rest.join("=")}return parsed}var import_error_utils=__toESM(require_dist(),1);var ListTelemetryClient=class extends TelemetryClient{trackCliFlagAll(all){all&&this.trackCliFlag("all")}trackCliOptionMeta(meta){meta&&meta.length>0&&this.trackCliOption({option:"meta",value:this.redactedValue})}trackCliOptionPolicy(policy){policy&&policy.length>0&&this.trackCliOption({option:"policy",value:this.redactedValue})}trackCliOptionEnvironment(environment){environment&&this.trackCliOption({option:"environment",value:this.redactedTargetName(environment)})}trackCliOptionNext(next){next&&this.trackCliOption({option:"next",value:this.redactedValue})}trackCliOptionLimit(limit){limit&&this.trackCliOption({option:"limit",value:this.redactedValue})}trackCliFlagProd(flag){flag&&this.trackCliFlag("prod")}trackCliFlagYes(flag){flag&&this.trackCliFlag("yes")}trackCliFlagConfirm(flag){flag&&this.trackCliFlag("confirm")}trackCliOptionStatus(status){status&&this.trackCliOption({option:"status",value:this.redactedValue})}trackCliArgumentApp(app){app&&this.trackCliArgument({arg:"app",value:this.redactedValue})}trackCliFlagJson(json){json&&this.trackCliFlag("json")}};function toDate(timestamp){let date=new Date(timestamp),options={year:"2-digit",month:"2-digit",day:"2-digit"};return date.toLocaleDateString("en-US",options)}async function list(client){let{print,log,warn,error,note,debug,spinner}=output_manager_default,parsedArgs=null,flagsSpecification=getFlagsSpecification(listCommand.options);try{parsedArgs=parseArguments(client.argv.slice(2),flagsSpecification)}catch(error2){return printError(error2),2}let telemetry=new ListTelemetryClient({opts:{store:client.telemetryEventStore}});if(parsedArgs.flags["--help"])return telemetry.trackCliFlagHelp("list"),print(help(listCommand,{columns:client.stderr.columns})),0;let validationResult=validateLsArgs({commandName:"ls [app]",args:parsedArgs.args,maxArgs:2,exitCode:2});if(validationResult!==0)return validationResult;let formatResult=validateJsonOutput(parsedArgs.flags);if(!formatResult.valid)return error(formatResult.error),2;let asJson=formatResult.jsonOutput;telemetry.trackCliFlagAll(parsedArgs.flags["--all"]),telemetry.trackCliFlagProd(parsedArgs.flags["--prod"]),telemetry.trackCliFlagYes(parsedArgs.flags["--yes"]),telemetry.trackCliOptionEnvironment(parsedArgs.flags["--environment"]),telemetry.trackCliOptionMeta(parsedArgs.flags["--meta"]),telemetry.trackCliOptionNext(parsedArgs.flags["--next"]),telemetry.trackCliOptionLimit(parsedArgs.flags["--limit"]),telemetry.trackCliOptionFormat(parsedArgs.flags["--format"]),telemetry.trackCliOptionPolicy(parsedArgs.flags["--policy"]),telemetry.trackCliOptionStatus(parsedArgs.flags["--status"]),"--confirm"in parsedArgs.flags&&(telemetry.trackCliFlagConfirm(parsedArgs.flags["--confirm"]),warn("`--confirm` is deprecated, please use `--yes` instead"),parsedArgs.flags["--yes"]=parsedArgs.flags["--confirm"]);let meta=parseMeta(parsedArgs.flags["--meta"]),policy=parsePolicy(parsedArgs.flags["--policy"]),target=parseTarget({flagName:"environment",flags:parsedArgs.flags}),statusFlag=parsedArgs.flags["--status"],status;if(statusFlag){let validStatuses=["BUILDING","ERROR","INITIALIZING","QUEUED","READY","CANCELED","BLOCKED"],statusValues=statusFlag.split(",").map(s=>s.trim().toUpperCase()),invalidStatuses=statusValues.filter(s=>!validStatuses.includes(s));if(invalidStatuses.length>0)return error(`Invalid status values: ${invalidStatuses.join(", ")}. Valid values are: ${validStatuses.join(", ")}`),1;status=statusValues.join(",")}let project,pagination,contextName="",app=parsedArgs.args[1],deployments=[],singleDeployment=!1,allFlag=parsedArgs.flags["--all"],showAllProjects=!1;if(allFlag&&app)return error("Cannot use --all flag with a project argument"),2;if(app){if(!isValidName(app))return error(`The provided argument "${app}" is not a valid project name`),2;if(telemetry.trackCliArgumentApp(app),app.includes(".")){try{contextName=await getContextName(client)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&(err.code==="NOT_AUTHORIZED"||err.code==="TEAM_DELETED"))return error(err.message),1}if(!contextName)return error("No context name found"),1;let host=toHost(app),deployment=await getDeployment(client,contextName,host);if(!deployment.projectId)return error(`Could not find a deployment for "${host}"`),1;app=deployment.projectId,note(`We suggest using ${getCommandName("inspect <deployment>")} for retrieving details about a single deployment`),deployments.push(deployment),singleDeployment=!0}let p=await getProjectByNameOrId(client,app);if(p instanceof ProjectNotFound)return exitWithNonInteractiveError(client,p,1,{variant:"list",projectName:app}),error(`The provided argument "${app}" is not a valid project name`),1;project=p}else if(allFlag)showAllProjects=!0;else{let link=await getLinkedProject(client,{cwd:client.cwd});if(link.status==="error")return link.exitCode;link.status==="linked"?(project=link.project,client.config.currentTeam=link.org.id):showAllProjects=!0}if(!contextName)try{contextName=await getContextName(client)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&(err.code==="NOT_AUTHORIZED"||err.code==="TEAM_DELETED"))return error(err.message),1}let nextTimestamp,limitFlag;try{[nextTimestamp,limitFlag]=getPaginationOpts(parsedArgs.flags)}catch(err){return printError(err),1}let limit=limitFlag??20,projectSlugLink=project?formatProject(contextName,project.name):null;if(!singleDeployment){asJson||spinner(`Fetching deployments in ${import_chalk.default.bold(contextName)}`);let start=Date.now();debug("Fetching deployments");let query=new URLSearchParams({limit:String(limit)});project&&query.set("projectId",project.id);for(let[k,v]of Object.entries(meta))query.set(`meta-${k}`,v);for(let[k,v]of Object.entries(policy))query.set(`policy-${k}`,v);nextTimestamp&&query.set("until",String(nextTimestamp)),target&&query.set("target",target),status&&query.set("state",status);for await(let chunk of client.fetchPaginated(`/v6/deployments?${query}`))if(deployments.push(...chunk.deployments),pagination=chunk.pagination,deployments.length>=limit)break;if(deployments.length=Math.min(deployments.length,limit),!deployments.length){if(asJson){let jsonOutput={deployments:[],pagination,contextName};client.stdout.write(`${JSON.stringify(jsonOutput,null,2)}
7
+ import{getPaginationOpts,isValidName}from"../../chunks/chunk-ILFUNCJZ.js";import{getCommandFlags}from"../../chunks/chunk-OUHPDA7Q.js";import{parseMeta}from"../../chunks/chunk-CZSOZKHX.js";import{formatEnvironment}from"../../chunks/chunk-CYV3X62I.js";import{validateLsArgs}from"../../chunks/chunk-DNDBPLLI.js";import{formatProject}from"../../chunks/chunk-WYI4VNXT.js";import{elapsed}from"../../chunks/chunk-Q7D7RGXM.js";import{parseTarget}from"../../chunks/chunk-2B3A3MOX.js";import{getDeployment,toHost}from"../../chunks/chunk-IVIZLWZQ.js";import"../../chunks/chunk-HVUJNVPS.js";import{listCommand}from"../../chunks/chunk-UCAE5Z5L.js";import{help}from"../../chunks/chunk-H3KYG32S.js";import{table}from"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-QAETJRKX.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{validateJsonOutput}from"../../chunks/chunk-D4MW3RDW.js";import{getContextName}from"../../chunks/chunk-IIC2A4YN.js";import{TelemetryClient}from"../../chunks/chunk-KUGXOLL7.js";import"../../chunks/chunk-MV4WHUIC.js";import"../../chunks/chunk-VKXEOL4K.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import"../../chunks/chunk-NWGBDBZI.js";import"../../chunks/chunk-4SAVH3H7.js";import"../../chunks/chunk-ZS2WS4AM.js";import"../../chunks/chunk-AOWWC6WZ.js";import"../../chunks/chunk-MY4MONOH.js";import{parseArguments}from"../../chunks/chunk-ELDHGU6N.js";import{exitWithNonInteractiveError}from"../../chunks/chunk-BAT6SDBJ.js";import{getFlagsSpecification}from"../../chunks/chunk-MI7W4QMV.js";import{getLinkedProject,getProjectByNameOrId}from"../../chunks/chunk-U3NQZJQ4.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import"../../chunks/chunk-IJCCFLCQ.js";import"../../chunks/chunk-ZQME5XUJ.js";import"../../chunks/chunk-2VBFQZ72.js";import{ProjectNotFound}from"../../chunks/chunk-XSDAUM4F.js";import{getCommandName,require_lib}from"../../chunks/chunk-JESNVRVR.js";import{output_manager_default}from"../../chunks/chunk-M774HRX5.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_ms=__toESM(require_ms(),1),import_chalk=__toESM(require_source(),1),import_title=__toESM(require_lib(),1);function parsePolicy(policy){if(!policy)return{};typeof policy=="string"&&(policy=[policy]);let parsed={};for(let item of policy){let[key,...rest]=item.split("=");parsed[key]=rest.join("=")}return parsed}var import_error_utils=__toESM(require_dist(),1);var ListTelemetryClient=class extends TelemetryClient{trackCliFlagAll(all){all&&this.trackCliFlag("all")}trackCliOptionMeta(meta){meta&&meta.length>0&&this.trackCliOption({option:"meta",value:this.redactedValue})}trackCliOptionPolicy(policy){policy&&policy.length>0&&this.trackCliOption({option:"policy",value:this.redactedValue})}trackCliOptionEnvironment(environment){environment&&this.trackCliOption({option:"environment",value:this.redactedTargetName(environment)})}trackCliOptionNext(next){next&&this.trackCliOption({option:"next",value:this.redactedValue})}trackCliOptionLimit(limit){limit&&this.trackCliOption({option:"limit",value:this.redactedValue})}trackCliFlagProd(flag){flag&&this.trackCliFlag("prod")}trackCliFlagYes(flag){flag&&this.trackCliFlag("yes")}trackCliFlagConfirm(flag){flag&&this.trackCliFlag("confirm")}trackCliOptionStatus(status){status&&this.trackCliOption({option:"status",value:this.redactedValue})}trackCliArgumentApp(app){app&&this.trackCliArgument({arg:"app",value:this.redactedValue})}trackCliFlagJson(json){json&&this.trackCliFlag("json")}};function toDate(timestamp){let date=new Date(timestamp),options={year:"2-digit",month:"2-digit",day:"2-digit"};return date.toLocaleDateString("en-US",options)}async function list(client){let{print,log,warn,error,note,debug,spinner}=output_manager_default,parsedArgs=null,flagsSpecification=getFlagsSpecification(listCommand.options);try{parsedArgs=parseArguments(client.argv.slice(2),flagsSpecification)}catch(error2){return printError(error2),2}let telemetry=new ListTelemetryClient({opts:{store:client.telemetryEventStore}});if(parsedArgs.flags["--help"])return telemetry.trackCliFlagHelp("list"),print(help(listCommand,{columns:client.stderr.columns})),0;let validationResult=validateLsArgs({commandName:"ls [app]",args:parsedArgs.args,maxArgs:2,exitCode:2});if(validationResult!==0)return validationResult;let formatResult=validateJsonOutput(parsedArgs.flags);if(!formatResult.valid)return error(formatResult.error),2;let asJson=formatResult.jsonOutput;telemetry.trackCliFlagAll(parsedArgs.flags["--all"]),telemetry.trackCliFlagProd(parsedArgs.flags["--prod"]),telemetry.trackCliFlagYes(parsedArgs.flags["--yes"]),telemetry.trackCliOptionEnvironment(parsedArgs.flags["--environment"]),telemetry.trackCliOptionMeta(parsedArgs.flags["--meta"]),telemetry.trackCliOptionNext(parsedArgs.flags["--next"]),telemetry.trackCliOptionLimit(parsedArgs.flags["--limit"]),telemetry.trackCliOptionFormat(parsedArgs.flags["--format"]),telemetry.trackCliOptionPolicy(parsedArgs.flags["--policy"]),telemetry.trackCliOptionStatus(parsedArgs.flags["--status"]),"--confirm"in parsedArgs.flags&&(telemetry.trackCliFlagConfirm(parsedArgs.flags["--confirm"]),warn("`--confirm` is deprecated, please use `--yes` instead"),parsedArgs.flags["--yes"]=parsedArgs.flags["--confirm"]);let meta=parseMeta(parsedArgs.flags["--meta"]),policy=parsePolicy(parsedArgs.flags["--policy"]),target=parseTarget({flagName:"environment",flags:parsedArgs.flags}),statusFlag=parsedArgs.flags["--status"],status;if(statusFlag){let validStatuses=["BUILDING","ERROR","INITIALIZING","QUEUED","READY","CANCELED","BLOCKED"],statusValues=statusFlag.split(",").map(s=>s.trim().toUpperCase()),invalidStatuses=statusValues.filter(s=>!validStatuses.includes(s));if(invalidStatuses.length>0)return error(`Invalid status values: ${invalidStatuses.join(", ")}. Valid values are: ${validStatuses.join(", ")}`),1;status=statusValues.join(",")}let project,pagination,contextName="",app=parsedArgs.args[1],deployments=[],singleDeployment=!1,allFlag=parsedArgs.flags["--all"],showAllProjects=!1;if(allFlag&&app)return error("Cannot use --all flag with a project argument"),2;if(app){if(!isValidName(app))return error(`The provided argument "${app}" is not a valid project name`),2;if(telemetry.trackCliArgumentApp(app),app.includes(".")){try{contextName=await getContextName(client)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&(err.code==="NOT_AUTHORIZED"||err.code==="TEAM_DELETED"))return error(err.message),1}if(!contextName)return error("No context name found"),1;let host=toHost(app),deployment=await getDeployment(client,contextName,host);if(!deployment.projectId)return error(`Could not find a deployment for "${host}"`),1;app=deployment.projectId,note(`We suggest using ${getCommandName("inspect <deployment>")} for retrieving details about a single deployment`),deployments.push(deployment),singleDeployment=!0}let p=await getProjectByNameOrId(client,app);if(p instanceof ProjectNotFound)return exitWithNonInteractiveError(client,p,1,{variant:"list",projectName:app}),error(`The provided argument "${app}" is not a valid project name`),1;project=p}else if(allFlag)showAllProjects=!0;else{let link=await getLinkedProject(client,{cwd:client.cwd});if(link.status==="error")return link.exitCode;link.status==="linked"?(project=link.project,client.config.currentTeam=link.org.id):showAllProjects=!0}if(!contextName)try{contextName=await getContextName(client)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&(err.code==="NOT_AUTHORIZED"||err.code==="TEAM_DELETED"))return error(err.message),1}let nextTimestamp,limitFlag;try{[nextTimestamp,limitFlag]=getPaginationOpts(parsedArgs.flags)}catch(err){return printError(err),1}let limit=limitFlag??20,projectSlugLink=project?formatProject(contextName,project.name):null;if(!singleDeployment){asJson||spinner(`Fetching deployments in ${import_chalk.default.bold(contextName)}`);let start=Date.now();debug("Fetching deployments");let query=new URLSearchParams({limit:String(limit)});project&&query.set("projectId",project.id);for(let[k,v]of Object.entries(meta))query.set(`meta-${k}`,v);for(let[k,v]of Object.entries(policy))query.set(`policy-${k}`,v);nextTimestamp&&query.set("until",String(nextTimestamp)),target&&query.set("target",target),status&&query.set("state",status);for await(let chunk of client.fetchPaginated(`/v6/deployments?${query}`))if(deployments.push(...chunk.deployments),pagination=chunk.pagination,deployments.length>=limit)break;if(deployments.length=Math.min(deployments.length,limit),!deployments.length){if(asJson){let jsonOutput={deployments:[],pagination,contextName};client.stdout.write(`${JSON.stringify(jsonOutput,null,2)}
8
8
  `)}else log(`No deployments found under ${import_chalk.default.bold(contextName)}.`);return 0}if(!asJson){let deploymentsLabel=target==="production"?"Production deployments":"Deployments";log(showAllProjects?`${deploymentsLabel} under ${import_chalk.default.bold(contextName)} ${elapsed(Date.now()-start)}`:`${deploymentsLabel} for ${projectSlugLink} ${elapsed(Date.now()-start)}`)}}if(asJson){let jsonOutput={contextName,deployments:deployments.sort(sortByCreatedAt).map(dep=>({id:dep.id,url:dep.url,name:dep.name,state:dep.readyState,target:dep.target,customEnvironment:dep.customEnvironment?{id:dep.customEnvironment.id,slug:dep.customEnvironment.slug}:void 0,createdAt:dep.createdAt,buildingAt:dep.buildingAt,ready:dep.ready,creator:dep.creator?{uid:dep.creator.uid,username:dep.creator.username}:void 0,meta:dep.meta})),pagination};return client.stdout.write(`${JSON.stringify(jsonOutput,null,2)}
9
9
  `),0}let headers=["Age","Project","Deployment","Status","Environment"],showPolicy=Object.keys(policy).length>0;showPolicy||headers.push("Duration","Username"),showPolicy&&headers.push("Proposed Expiration");let urls=[],tablePrint=table([headers.map(header=>import_chalk.default.bold(import_chalk.default.cyan(header))),...deployments.sort(sortByCreatedAt).map(dep=>{urls.push(`https://${dep.url}`);let proposedExp=dep.proposedExpiration?toDate(Math.min(Date.now(),dep.proposedExpiration)):"No expiration",createdAt=(0,import_ms.default)(Date.now()-(dep?.undeletedAt??dep.createdAt)),targetName=dep.customEnvironment?.slug||(dep.target==="production"?"Production":"Preview"),targetSlug=dep.customEnvironment?.id||dep.target||"preview";return[import_chalk.default.gray(createdAt),formatProject(contextName,dep.name),`https://${dep.url}`,stateString(dep.readyState||""),formatEnvironment(contextName,dep.name,{id:targetSlug,slug:targetName}),...showPolicy?[]:[import_chalk.default.gray(getDeploymentDuration(dep))],...showPolicy?[]:[import_chalk.default.gray(dep.creator?.username)],...showPolicy?[import_chalk.default.gray(proposedExp)]:[]]}).filter(app2=>app2===null?filterUniqueApps():()=>!0)],{hsep:5}).replace(/^/gm," ");if(print(`
10
10
  ${tablePrint}