vercel 62.5.0 → 62.7.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 (169) hide show
  1. package/README.md +2 -0
  2. package/dist/chunks/{add-SUDX7R63.js → add-OXHI3PVM.js} +1 -1
  3. package/dist/chunks/{add-UNQJB3SM.js → add-P3FNSVMN.js} +1 -1
  4. package/dist/chunks/{add-HN4OXQLM.js → add-WUT6QU2J.js} +1 -1
  5. package/dist/chunks/{build-BRMOQZHW.js → build-J6VW3KHT.js} +1 -1
  6. package/dist/chunks/{chunk-B3MYIRFE.js → chunk-2KSNNB4B.js} +1 -1
  7. package/dist/chunks/{chunk-QMTPSHRV.js → chunk-3XLK5ZPD.js} +5 -5
  8. package/dist/chunks/{chunk-TEYG3UZQ.js → chunk-3ZMD36SU.js} +1 -1
  9. package/dist/chunks/{chunk-TG6SMD7D.js → chunk-46UCIIJN.js} +1 -1
  10. package/dist/chunks/{chunk-XMV7OSFJ.js → chunk-4H5LPD3T.js} +1 -1
  11. package/dist/chunks/{chunk-PQV3QNDG.js → chunk-4KQBTIMZ.js} +1 -1
  12. package/dist/chunks/{chunk-QCOPZAUC.js → chunk-4QSVBLAS.js} +1 -1
  13. package/dist/chunks/{chunk-WNG72BRT.js → chunk-5AXNGQJC.js} +1 -1
  14. package/dist/chunks/{chunk-DOWDSQPG.js → chunk-5JN3FWV2.js} +1 -1
  15. package/dist/chunks/{chunk-PY6YO4MR.js → chunk-5M45EBVX.js} +2 -2
  16. package/dist/chunks/{chunk-X7F3567X.js → chunk-5ZQF5WIO.js} +1 -1
  17. package/dist/chunks/{chunk-6LOW7CGD.js → chunk-6DJ6PMEK.js} +1 -1
  18. package/dist/chunks/{chunk-NDZOUAFO.js → chunk-6EW4BCMR.js} +1 -1
  19. package/dist/chunks/{chunk-RHUAFRZX.js → chunk-A73N3QKT.js} +1 -1
  20. package/dist/chunks/{chunk-CAAD55US.js → chunk-AEEEEOYS.js} +1 -1
  21. package/dist/chunks/chunk-APSIFBD4.js +7 -0
  22. package/dist/chunks/{chunk-MCOJUSDV.js → chunk-B2L2QTXT.js} +1 -1
  23. package/dist/chunks/{chunk-ZXDS7NJI.js → chunk-BHBNTQRT.js} +1 -1
  24. package/dist/chunks/{chunk-OYWYHFXV.js → chunk-CF2PIWRO.js} +1 -1
  25. package/dist/chunks/{chunk-733ZK37Y.js → chunk-CR2ZQBDU.js} +1 -1
  26. package/dist/chunks/{chunk-5CSWEE7J.js → chunk-CRITS7IX.js} +1 -1
  27. package/dist/chunks/{chunk-4BRFG5HP.js → chunk-DGH5CD6D.js} +1 -1
  28. package/dist/chunks/{chunk-PD3ZD52Q.js → chunk-ECMWDZTJ.js} +4 -4
  29. package/dist/chunks/{chunk-AMSFO2VK.js → chunk-EQ24OC5G.js} +1 -1
  30. package/dist/chunks/{chunk-D6JBONML.js → chunk-FAJB3JV5.js} +1 -1
  31. package/dist/chunks/chunk-FB3U3RAM.js +9 -0
  32. package/dist/chunks/{chunk-72YTT324.js → chunk-FEEG5UU2.js} +1 -1
  33. package/dist/chunks/{chunk-5NSYN7IO.js → chunk-FQJCWZ4C.js} +1 -1
  34. package/dist/chunks/{chunk-LGFCHU75.js → chunk-GMTLVRN7.js} +1 -1
  35. package/dist/chunks/{chunk-UXAYYF6I.js → chunk-GUTZ45DE.js} +1 -1
  36. package/dist/chunks/{chunk-5QVOIOPN.js → chunk-I5JR7PIO.js} +1 -1
  37. package/dist/chunks/{chunk-ST2X5QRA.js → chunk-IEKUTNKT.js} +1 -1
  38. package/dist/chunks/{chunk-L57FNGBV.js → chunk-K2RQEX7N.js} +1 -1
  39. package/dist/chunks/{chunk-O552UV4H.js → chunk-KXMVFT2K.js} +1 -1
  40. package/dist/chunks/{chunk-ZX2JOGOA.js → chunk-LCH3SUJ7.js} +1 -1
  41. package/dist/chunks/{chunk-HVJERSGE.js → chunk-LWQVT6YW.js} +1 -1
  42. package/dist/chunks/chunk-LXNMVWYO.js +9 -0
  43. package/dist/chunks/{chunk-MQW6DKD2.js → chunk-LYKPLTZ7.js} +1 -1
  44. package/dist/chunks/chunk-M3HO5CTQ.js +7 -0
  45. package/dist/chunks/{chunk-WJZV7BI4.js → chunk-M4IVLSNQ.js} +1 -1
  46. package/dist/chunks/{chunk-ILR6YA2A.js → chunk-M5NWE7EO.js} +1 -1
  47. package/dist/chunks/{chunk-3J2P52OU.js → chunk-MCBO6LL7.js} +2 -2
  48. package/dist/chunks/{chunk-2FQCZE6S.js → chunk-MIG67KZ2.js} +1 -1
  49. package/dist/chunks/{chunk-4WS3D23J.js → chunk-NM67DIPQ.js} +1 -1
  50. package/dist/chunks/{chunk-W6M24BQ4.js → chunk-NYFB3EYC.js} +1 -1
  51. package/dist/chunks/chunk-O3UY73UQ.js +7 -0
  52. package/dist/chunks/chunk-ONPJXQQ6.js +10 -0
  53. package/dist/chunks/chunk-ORJGSUQT.js +9 -0
  54. package/dist/chunks/{chunk-HRQQ2N5B.js → chunk-PE7QZUY7.js} +1 -1
  55. package/dist/chunks/{chunk-MR423MWE.js → chunk-Q2YQSMIB.js} +6 -6
  56. package/dist/chunks/{chunk-C7SLCL3Z.js → chunk-Q7AYTXUR.js} +1 -1
  57. package/dist/chunks/{chunk-EPBZNTIJ.js → chunk-QZ2G3AMY.js} +1 -1
  58. package/dist/chunks/{chunk-P3ZZVBZQ.js → chunk-RMZJP32R.js} +1 -1
  59. package/dist/chunks/{chunk-P3YADO62.js → chunk-RSLPLRVK.js} +1 -1
  60. package/dist/chunks/{chunk-AJT64XO2.js → chunk-RYMRVMGD.js} +2 -2
  61. package/dist/chunks/{chunk-MHKDLJEI.js → chunk-SMC4MGY5.js} +1 -1
  62. package/dist/chunks/{chunk-ZFYW4CEL.js → chunk-SR5XEF7L.js} +1 -1
  63. package/dist/chunks/{chunk-PTKSYVXM.js → chunk-TAT5WGDZ.js} +1 -1
  64. package/dist/chunks/{chunk-GXNSAACA.js → chunk-THB7KY2N.js} +1 -1
  65. package/dist/chunks/{chunk-TNGDWVMX.js → chunk-UKMRJIIZ.js} +1 -1
  66. package/dist/chunks/{chunk-MUJP4VPF.js → chunk-UKVEXM5O.js} +1 -1
  67. package/dist/chunks/{chunk-MJWC4W6J.js → chunk-ULHETT7U.js} +1 -1
  68. package/dist/chunks/{chunk-2E6XILZC.js → chunk-UOZHC2ZG.js} +1 -1
  69. package/dist/chunks/{chunk-RERUTI3O.js → chunk-V426AGVC.js} +2 -2
  70. package/dist/chunks/{chunk-6ALOD3OE.js → chunk-V6Y6UK6B.js} +2 -4
  71. package/dist/chunks/{chunk-DWPCZHDT.js → chunk-VWBJWUYQ.js} +1 -1
  72. package/dist/chunks/{chunk-TN4IR2LY.js → chunk-WNTA7DCC.js} +1 -1
  73. package/dist/chunks/{chunk-VMHUBZRU.js → chunk-XQQ7DTQG.js} +1 -1
  74. package/dist/chunks/{chunk-UKC3NSS6.js → chunk-YEWZFZ2O.js} +1 -1
  75. package/dist/chunks/{chunk-P4BGC5RL.js → chunk-YGMOJBSP.js} +2 -2
  76. package/dist/chunks/{chunk-65Z5UPUC.js → chunk-YKOIVWZI.js} +1 -1
  77. package/dist/chunks/{chunk-X7U35FBE.js → chunk-YTIANIL7.js} +1 -1
  78. package/dist/chunks/chunk-YUDKK2QJ.js +7 -0
  79. package/dist/chunks/{chunk-DQXGNNPB.js → chunk-YZBYL3SH.js} +1 -1
  80. package/dist/chunks/{chunk-4AY4YYKS.js → chunk-ZN37NQM4.js} +1 -1
  81. package/dist/chunks/{chunk-W45NZSSK.js → chunk-ZNQI6M3S.js} +1 -1
  82. package/dist/chunks/{clear-M6LODAMD.js → clear-VMJVLPVR.js} +1 -1
  83. package/dist/chunks/{compile-vercel-config-NBX5UWHW.js → compile-vercel-config-YCLXPL5H.js} +1 -1
  84. package/dist/chunks/{config-Q3TRA4NK.js → config-JPX6NJMJ.js} +1 -1
  85. package/dist/chunks/{config-YQ7FIAFK.js → config-YMUUPO3R.js} +1 -1
  86. package/dist/chunks/config-validator.mjs +1 -1
  87. package/dist/chunks/{connect-git-provider-67DJOI6X.js → connect-git-provider-KLSBCSD2.js} +1 -1
  88. package/dist/chunks/{delete-KSZ7R5V6.js → delete-E7J4B5E5.js} +1 -1
  89. package/dist/chunks/{delete-NRWKSTCN.js → delete-EEY7M6XT.js} +1 -1
  90. package/dist/chunks/{detect-services-MWYUJZJZ.js → detect-services-E2TWAKQS.js} +1 -1
  91. package/dist/chunks/{disable-BUGWQUS7.js → disable-5TKY6JK2.js} +1 -1
  92. package/dist/chunks/{discard-J5O3C753.js → discard-ALSOF66H.js} +1 -1
  93. package/dist/chunks/{edit-DMOIBVEP.js → edit-2M3KEE3H.js} +1 -1
  94. package/dist/chunks/{edit-YRWAXGEI.js → edit-ISUCMYNW.js} +1 -1
  95. package/dist/chunks/{enable-IL27VHSU.js → enable-2QTTTYQD.js} +1 -1
  96. package/dist/chunks/{exec-GYSSNCNK.js → exec-XIQJ2A3J.js} +1 -1
  97. package/dist/chunks/{export-HBUUGMGE.js → export-PV2NDS7C.js} +1 -1
  98. package/dist/chunks/{future-BXETJ6CT.js → future-SQS5POAL.js} +1 -1
  99. package/dist/chunks/{generate-cert-for-deploy-K5QDHEEQ.js → generate-cert-for-deploy-4EJRA7MS.js} +1 -1
  100. package/dist/chunks/{image-M2XIQYXT.js → image-6GL2UOA2.js} +1 -1
  101. package/dist/chunks/{import-builders-UGIWTKRS.js → import-builders-KAZMYQCR.js} +1 -1
  102. package/dist/chunks/{inspect-SUEMHSB6.js → inspect-3HGROSZO.js} +1 -1
  103. package/dist/chunks/{inspect-XANEFWYN.js → inspect-FK6GC5JZ.js} +1 -1
  104. package/dist/chunks/{inspect-TDHISMRV.js → inspect-LZMU7RIU.js} +1 -1
  105. package/dist/chunks/{inspect-HASOG2PB.js → inspect-ORVORGUM.js} +1 -1
  106. package/dist/chunks/{inspect-OGUGKPVK.js → inspect-UNL54246.js} +1 -1
  107. package/dist/chunks/{list-32NXD7OW.js → list-EWJI2WSQ.js} +1 -1
  108. package/dist/chunks/{list-Q566PTT4.js → list-FVUIZPC7.js} +1 -1
  109. package/dist/chunks/{list-Z6DRFZ7F.js → list-WOUJM4WR.js} +1 -1
  110. package/dist/chunks/{login-GPCBSMHV.js → login-IJLY5XTT.js} +1 -1
  111. package/dist/chunks/{login-A6R3RQIW.js → login-JREQ7SLY.js} +1 -1
  112. package/dist/chunks/{logs-L33R4G67.js → logs-Z7IMGFO2.js} +1 -1
  113. package/dist/chunks/{ls-VSK2ZFSY.js → ls-4COX4SMJ.js} +1 -1
  114. package/dist/chunks/{ls-6CYMQBX3.js → ls-6CD2OQGA.js} +1 -1
  115. package/dist/chunks/{ls-CTIACPC5.js → ls-6DOYSBQM.js} +1 -1
  116. package/dist/chunks/{ls-DUCIK4E6.js → ls-AHT2FRGM.js} +1 -1
  117. package/dist/chunks/{ls-R442RADW.js → ls-LXBUE4LZ.js} +1 -1
  118. package/dist/chunks/{ls-JPL3AFIM.js → ls-RBWPVJ5G.js} +1 -1
  119. package/dist/chunks/{ls-GDR45ANC.js → ls-W5SJUIHD.js} +1 -1
  120. package/dist/chunks/{mutate-MUWQVZKM.js → mutate-TVUHBRBK.js} +1 -1
  121. package/dist/chunks/{notifications-YKGIFXKO.js → notifications-OXOSD6UK.js} +1 -1
  122. package/dist/chunks/{open-OJAIEDS5.js → open-SWPHB54M.js} +1 -1
  123. package/dist/chunks/{openapi-Y4NWAKUM.js → openapi-32XHDVJL.js} +1 -1
  124. package/dist/chunks/{permissions-LWKZBBU7.js → permissions-A4WMGETJ.js} +1 -1
  125. package/dist/chunks/{prompt-missing-credentials-O3GGMOZH.js → prompt-missing-credentials-6IXO6VND.js} +1 -1
  126. package/dist/chunks/{publish-JHNLZT6K.js → publish-2CS4RYJW.js} +1 -1
  127. package/dist/chunks/pull-WWUH4M5V.js +7 -0
  128. package/dist/chunks/{purchase-domain-if-available-CJK3G4DT.js → purchase-domain-if-available-TAXCYIV7.js} +1 -1
  129. package/dist/chunks/{push-MUMGVOSY.js → push-OPRW7M4I.js} +1 -1
  130. package/dist/chunks/{query-2TTSDOFF.js → query-22PGP7BC.js} +1 -1
  131. package/dist/chunks/{reauthenticate-S47X66LM.js → reauthenticate-LMR25CIE.js} +1 -1
  132. package/dist/chunks/{reorder-NGBZWNZH.js → reorder-Y3NMEA2S.js} +1 -1
  133. package/dist/chunks/{reply-5WF5YHOM.js → reply-YEZHST2Q.js} +1 -1
  134. package/dist/chunks/{resolve-MPZBUK5V.js → resolve-QC37E2EB.js} +1 -1
  135. package/dist/chunks/{restore-NVY4A3T3.js → restore-RMQVGYQB.js} +1 -1
  136. package/dist/chunks/{rm-ZO5JP3GF.js → rm-42U6SPVV.js} +1 -1
  137. package/dist/chunks/{rm-HFJCOK2D.js → rm-43MPIHP3.js} +1 -1
  138. package/dist/chunks/{rm-QXQ2AD4R.js → rm-4MSUYUEP.js} +1 -1
  139. package/dist/chunks/{rm-DB5K2RI7.js → rm-DPHE34CD.js} +1 -1
  140. package/dist/chunks/{rm-SMKVHN75.js → rm-JHWXYHJY.js} +1 -1
  141. package/dist/chunks/{routes-KO5NFCCJ.js → routes-2GTCE542.js} +1 -1
  142. package/dist/chunks/{rule-inspect-VZARLRS3.js → rule-inspect-7LIPL5YY.js} +1 -1
  143. package/dist/chunks/{rules-G2WFYCPB.js → rules-6KWBVUF2.js} +1 -1
  144. package/dist/chunks/{schema-SVYU72YU.js → schema-OUFU5V7Z.js} +1 -1
  145. package/dist/chunks/{schema-G6BOZBNB.js → schema-S2DE7S5N.js} +1 -1
  146. package/dist/chunks/{select-org-2W67WKBG.js → select-org-EL66MG67.js} +1 -1
  147. package/dist/chunks/{set-ILVKMTUD.js → set-VXSNREF4.js} +1 -1
  148. package/dist/chunks/setup-and-link-I7SGZNGO.js +7 -0
  149. package/dist/chunks/{tags-C34XXMYO.js → tags-AGLQDT3Z.js} +1 -1
  150. package/dist/chunks/{types-MATC4UQL.js → types-GQNKYZJH.js} +1 -1
  151. package/dist/chunks/{update-IVWOZO4P.js → update-TI3YRVQT.js} +1 -1
  152. package/dist/commands/build/index.js +7 -7
  153. package/dist/commands/deploy/index.js +44 -28
  154. package/dist/commands/dev/index.js +8 -8
  155. package/dist/commands/env/index.js +1 -1
  156. package/dist/commands/link/index.js +1 -1
  157. package/dist/commands/list/index.js +1 -1
  158. package/dist/commands-bulk.js +35 -39
  159. package/dist/index.js +6 -5
  160. package/dist/internal-build.js +1 -1
  161. package/dist/version.mjs +1 -1
  162. package/package.json +54 -53
  163. package/dist/chunks/chunk-2Z47VG5H.js +0 -9
  164. package/dist/chunks/chunk-EA3BJUUK.js +0 -7
  165. package/dist/chunks/chunk-EJNFKH6Y.js +0 -10
  166. package/dist/chunks/chunk-NTRM6VO6.js +0 -9
  167. package/dist/chunks/chunk-SX64OM5A.js +0 -7
  168. package/dist/chunks/pull-E4K6BVQW.js +0 -7
  169. package/dist/chunks/setup-and-link-VFCYLLB5.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-5QVOIOPN.js";import{loadVercelConfig,tryDetectServices}from"../../chunks/chunk-2E6XILZC.js";import"../../chunks/chunk-U4C2LU7H.js";import{import_write_build_result,require_detect_builders_with_services,require_get_files,require_mime_types,require_schedule_entrypoint,require_service_schedules}from"../../chunks/chunk-AMSFO2VK.js";import{importBuilders,require_npa}from"../../chunks/chunk-LGFCHU75.js";import"../../chunks/chunk-4CACOKMS.js";import"../../chunks/chunk-7RR7MIMT.js";import"../../chunks/chunk-B3MYIRFE.js";import"../../chunks/chunk-QHJLRTVY.js";import{require_fast_deep_equal}from"../../chunks/chunk-4MZK6JT6.js";import{getUpdateCommand}from"../../chunks/chunk-MHKDLJEI.js";import"../../chunks/chunk-KKS7XWEX.js";import{readJSONFile}from"../../chunks/chunk-P3ZZVBZQ.js";import"../../chunks/chunk-ZFYW4CEL.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-4BRFG5HP.js";import{validateConfig}from"../../chunks/chunk-SX64OM5A.js";import"../../chunks/chunk-TNGDWVMX.js";import"../../chunks/chunk-2H77IRPI.js";import{pickOverrides}from"../../chunks/chunk-X7F3567X.js";import{require_dist as require_dist5}from"../../chunks/chunk-AJT64XO2.js";import{require_brace_expansion,require_dist as require_dist3,require_dist2 as require_dist4,require_minimatch}from"../../chunks/chunk-G3NHWIPJ.js";import{require_main}from"../../chunks/chunk-D6JBONML.js";import"../../chunks/chunk-OHDEHZLX.js";import"../../chunks/chunk-M2W3HKV3.js";import"../../chunks/chunk-PHW54NU5.js";import"../../chunks/chunk-NNP5NITU.js";import{require_inherits}from"../../chunks/chunk-L3JDEHCQ.js";import"../../chunks/chunk-P2O5DOYE.js";import"../../chunks/chunk-RHUAFRZX.js";import{VERCEL_OIDC_TOKEN,pullEnvRecords}from"../../chunks/chunk-PY6YO4MR.js";import"../../chunks/chunk-DWPCZHDT.js";import"../../chunks/chunk-5NSYN7IO.js";import"../../chunks/chunk-ULLWCOYC.js";import"../../chunks/chunk-2FQCZE6S.js";import{require_json_parse_better_errors}from"../../chunks/chunk-N6CNMMSZ.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-OI263FBO.js";import"../../chunks/chunk-EA3BJUUK.js";import{printProjectNotFoundError}from"../../chunks/chunk-O552UV4H.js";import{require_frameworks}from"../../chunks/chunk-23NBYS6R.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-H3QRCTIJ.js";import{require_dist as require_dist2}from"../../chunks/chunk-FAW6NBLQ.js";import"../../chunks/chunk-2I64AYHG.js";import"../../chunks/chunk-HVJERSGE.js";import"../../chunks/chunk-SOJCELXH.js";import{param}from"../../chunks/chunk-SXUEGVWB.js";import"../../chunks/chunk-ILR6YA2A.js";import"../../chunks/chunk-MCOJUSDV.js";import"../../chunks/chunk-UKC3NSS6.js";import"../../chunks/chunk-DQXGNNPB.js";import{help}from"../../chunks/chunk-W6M24BQ4.js";import"../../chunks/chunk-6TAQ6OWD.js";import{printError}from"../../chunks/chunk-2Z47VG5H.js";import{buildCommandWithYes,outputActionRequired}from"../../chunks/chunk-EJNFKH6Y.js";import"../../chunks/chunk-WPS6JZF6.js";import"../../chunks/chunk-OSCCYU74.js";import{detectExplicitScope,getLocalPathConfig,highlight}from"../../chunks/chunk-GXNSAACA.js";import{getGlobalPathConfig}from"../../chunks/chunk-CAAD55US.js";import{require_ms}from"../../chunks/chunk-QTKJC2O5.js";import{TelemetryClient}from"../../chunks/chunk-3J2P52OU.js";import"../../chunks/chunk-RCTYVKM5.js";import{isNativeBinaryInstall}from"../../chunks/chunk-7T6TL3GQ.js";import"../../chunks/chunk-BRK4OB4B.js";import"../../chunks/chunk-GHM7V3GG.js";import"../../chunks/chunk-5XJNPXQK.js";import{directFetch}from"../../chunks/chunk-MY4MONOH.js";import{parseArguments}from"../../chunks/chunk-MQW6DKD2.js";import"../../chunks/chunk-BKV35LVB.js";import{getFlagsSpecification}from"../../chunks/chunk-5IPBCD7K.js";import{VERCEL_DIR,findRepoRoot,getLinkedProject,getVercelDirectory,require_lib,require_pluralize,resolveProjectCwd}from"../../chunks/chunk-QMTPSHRV.js";import"../../chunks/chunk-B4ATVYZW.js";import"../../chunks/chunk-F2ZWW2IO.js";import"../../chunks/chunk-PPCFQQSU.js";import{printAlignedLabel}from"../../chunks/chunk-QCOPZAUC.js";import"../../chunks/chunk-HRQQ2N5B.js";import"../../chunks/chunk-VOZEB6PD.js";import{CantParseJSONFile,LambdaSizeExceededError,MissingDotenvVarsError,NowError,require_bytes}from"../../chunks/chunk-4WS3D23J.js";import{cmd,getCommandName,getCommandNamePlain,getTitleName}from"../../chunks/chunk-FI772UVH.js";import{Diagnostic,defineDiagnostics,link_default,output_manager_default,require_build_utils}from"../../chunks/chunk-MR423MWE.js";import{require_dist}from"../../chunks/chunk-QGIQK47P.js";import{pkg_default}from"../../chunks/chunk-AVSPFBLM.js";import"../../chunks/chunk-XCJDGQO7.js";import"../../chunks/chunk-YPTLSODC.js";import"../../chunks/chunk-7HL2RPUO.js";import{require_source}from"../../chunks/chunk-U7KCDTCH.js";import{require_supports_color}from"../../chunks/chunk-N3ZZ7FHQ.js";import"../../chunks/chunk-GU6VIFR5.js";import{__commonJS,__require,__toESM}from"../../chunks/chunk-6L236MNA.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-I5JR7PIO.js";import{loadVercelConfig,tryDetectServices}from"../../chunks/chunk-UOZHC2ZG.js";import"../../chunks/chunk-U4C2LU7H.js";import{import_write_build_result,require_detect_builders_with_services,require_get_files,require_mime_types,require_schedule_entrypoint,require_service_schedules}from"../../chunks/chunk-EQ24OC5G.js";import{importBuilders,require_npa}from"../../chunks/chunk-GMTLVRN7.js";import"../../chunks/chunk-4CACOKMS.js";import"../../chunks/chunk-7RR7MIMT.js";import{LOCAL_SCHEDULES_SESSION_HEADER,createLocalSchedulesSession}from"../../chunks/chunk-O3UY73UQ.js";import"../../chunks/chunk-2KSNNB4B.js";import"../../chunks/chunk-QHJLRTVY.js";import{require_fast_deep_equal}from"../../chunks/chunk-4MZK6JT6.js";import{getUpdateCommand}from"../../chunks/chunk-SMC4MGY5.js";import{readJSONFile}from"../../chunks/chunk-RMZJP32R.js";import"../../chunks/chunk-SR5XEF7L.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-DGH5CD6D.js";import{validateConfig}from"../../chunks/chunk-APSIFBD4.js";import"../../chunks/chunk-UKMRJIIZ.js";import"../../chunks/chunk-2H77IRPI.js";import{pickOverrides}from"../../chunks/chunk-5ZQF5WIO.js";import{require_dist as require_dist5}from"../../chunks/chunk-RYMRVMGD.js";import{require_brace_expansion,require_dist as require_dist3,require_dist2 as require_dist4,require_minimatch}from"../../chunks/chunk-G3NHWIPJ.js";import{require_main}from"../../chunks/chunk-FAJB3JV5.js";import"../../chunks/chunk-OHDEHZLX.js";import"../../chunks/chunk-M2W3HKV3.js";import"../../chunks/chunk-PHW54NU5.js";import"../../chunks/chunk-KKS7XWEX.js";import"../../chunks/chunk-NNP5NITU.js";import{require_inherits}from"../../chunks/chunk-L3JDEHCQ.js";import"../../chunks/chunk-P2O5DOYE.js";import"../../chunks/chunk-A73N3QKT.js";import{VERCEL_OIDC_TOKEN}from"../../chunks/chunk-5M45EBVX.js";import"../../chunks/chunk-VWBJWUYQ.js";import{require_json_parse_better_errors}from"../../chunks/chunk-N6CNMMSZ.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-OI263FBO.js";import{pullEnvRecords}from"../../chunks/chunk-M3HO5CTQ.js";import{printProjectNotFoundError}from"../../chunks/chunk-KXMVFT2K.js";import"../../chunks/chunk-FQJCWZ4C.js";import"../../chunks/chunk-ULLWCOYC.js";import{require_frameworks}from"../../chunks/chunk-23NBYS6R.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-H3QRCTIJ.js";import{require_dist as require_dist2}from"../../chunks/chunk-FAW6NBLQ.js";import"../../chunks/chunk-2I64AYHG.js";import"../../chunks/chunk-LWQVT6YW.js";import"../../chunks/chunk-MIG67KZ2.js";import"../../chunks/chunk-SOJCELXH.js";import{param}from"../../chunks/chunk-SXUEGVWB.js";import"../../chunks/chunk-M5NWE7EO.js";import"../../chunks/chunk-B2L2QTXT.js";import"../../chunks/chunk-YEWZFZ2O.js";import"../../chunks/chunk-YZBYL3SH.js";import{help}from"../../chunks/chunk-NYFB3EYC.js";import"../../chunks/chunk-6TAQ6OWD.js";import{printError}from"../../chunks/chunk-LXNMVWYO.js";import{buildCommandWithYes,outputActionRequired}from"../../chunks/chunk-ONPJXQQ6.js";import"../../chunks/chunk-WPS6JZF6.js";import"../../chunks/chunk-OSCCYU74.js";import{detectExplicitScope,getLocalPathConfig,highlight}from"../../chunks/chunk-THB7KY2N.js";import{getGlobalPathConfig}from"../../chunks/chunk-AEEEEOYS.js";import{require_ms}from"../../chunks/chunk-QTKJC2O5.js";import{TelemetryClient}from"../../chunks/chunk-MCBO6LL7.js";import"../../chunks/chunk-RCTYVKM5.js";import{isNativeBinaryInstall}from"../../chunks/chunk-7T6TL3GQ.js";import"../../chunks/chunk-BRK4OB4B.js";import"../../chunks/chunk-GHM7V3GG.js";import"../../chunks/chunk-5XJNPXQK.js";import{directFetch}from"../../chunks/chunk-MY4MONOH.js";import{parseArguments}from"../../chunks/chunk-LYKPLTZ7.js";import"../../chunks/chunk-BKV35LVB.js";import{getFlagsSpecification}from"../../chunks/chunk-5IPBCD7K.js";import{VERCEL_DIR,findRepoRoot,getLinkedProject,getVercelDirectory,require_lib,require_pluralize,resolveProjectCwd}from"../../chunks/chunk-3XLK5ZPD.js";import"../../chunks/chunk-B4ATVYZW.js";import"../../chunks/chunk-F2ZWW2IO.js";import"../../chunks/chunk-PPCFQQSU.js";import{printAlignedLabel}from"../../chunks/chunk-4QSVBLAS.js";import"../../chunks/chunk-PE7QZUY7.js";import"../../chunks/chunk-VOZEB6PD.js";import{CantParseJSONFile,LambdaSizeExceededError,MissingDotenvVarsError,NowError,require_bytes}from"../../chunks/chunk-NM67DIPQ.js";import{cmd,getCommandName,getCommandNamePlain,getTitleName}from"../../chunks/chunk-FI772UVH.js";import{Diagnostic,defineDiagnostics,link_default,output_manager_default,require_build_utils}from"../../chunks/chunk-Q2YQSMIB.js";import{require_dist}from"../../chunks/chunk-QGIQK47P.js";import{pkg_default}from"../../chunks/chunk-AVSPFBLM.js";import"../../chunks/chunk-XCJDGQO7.js";import"../../chunks/chunk-YPTLSODC.js";import"../../chunks/chunk-7HL2RPUO.js";import{require_source}from"../../chunks/chunk-U7KCDTCH.js";import{require_supports_color}from"../../chunks/chunk-N3ZZ7FHQ.js";import"../../chunks/chunk-GU6VIFR5.js";import{__commonJS,__require,__toESM}from"../../chunks/chunk-6L236MNA.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+=`
@@ -38,7 +38,7 @@ globstar while`,file,fr,pattern,pr,swallowee),this.matchOne(file.slice(fr),patte
38
38
  `);callback(null,prefixed+`
39
39
  `)}else callback(null,"")},flush(callback){buffer?callback(null,`${labelPrefix} ${buffer}
40
40
  `):callback(null,"")}})},stdout=createTransform("stdout"),stderr=createTransform("stderr");return stdout.pipe(process.stdout),stderr.pipe(process.stderr),{stdout,stderr,cleanup:()=>{stdout.unpipe(process.stdout),stderr.unpipe(process.stderr),stdout.destroy(),stderr.destroy()}}}function getServiceRoutePrefixes(service){return(0,import_build_utils5.isQueueTriggeredService)(service)||(0,import_build_utils5.isWorkflowTriggeredService)(service)?[(0,import_build_utils5.getInternalServiceWorkerPathPrefix)(service.name)]:(0,import_build_utils5.isScheduleTriggeredService)(service)?[(0,import_build_utils5.getInternalServiceCronPathPrefix)(service.name)]:service.type==="web"?[service.routePrefix||"/"]:[]}function getEntrypointForService(builderSrc,entrypoint,dir){let resolved=builderSrc||entrypoint||"";if(dir&&dir!=="."){let prefix=dir.endsWith("/")?dir:`${dir}/`;resolved.startsWith(prefix)&&(resolved=resolved.slice(prefix.length))}return resolved}var FORCE_KILL_GRACE_MS=2e3,STOP_ALL_TIMEOUT_MS=8e3;function killGroup(pid,signal){try{return process.kill(-pid,signal),!0}catch(err){let code=err.code;if(code==="ESRCH"||code==="EPERM")return!1;throw err}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(err){return err.code==="EPERM"}}function waitForExit(pid,proc,timeoutMs){return proc&&(proc.exitCode!==null||proc.signalCode!==null)||!isProcessAlive(pid)?Promise.resolve(!0):new Promise(resolve3=>{let settled=!1,finish=died=>{settled||(settled=!0,clearInterval(poll),clearTimeout(deadline),proc&&proc.removeListener("exit",onExit),resolve3(died))},onExit=()=>finish(!0);proc&&proc.once("exit",onExit);let poll=setInterval(()=>{isProcessAlive(pid)||finish(!0)},100),deadline=setTimeout(()=>finish(!1),timeoutMs)})}var ServicesOrchestrator=class{constructor(options){this.managedServices=new Map;this.managedProcesses=new Map;this.servicePorts=new Map;this.installMeta={};this.cronTimers=[];this.stopping=!1;this.services=options.services,this.cwd=options.cwd,this.repoRoot=options.repoRoot,this.maxNameLength=Math.max(...options.services.map(s=>s.name.length)),this.proxyOrigin=options.proxyOrigin,this.resourceEndpoints=options.resourceEndpoints,this.envFilesValues=options.env,this.useImplicitEnvInjection=options.useImplicitEnvInjection,this.preferServiceBuilder=options.preferServiceBuilder??!1,this.onQueueSubscriptions=options.onQueueSubscriptions;let pythonWorkspaces=options.services.filter(service=>service.runtime==="python").map(service=>path2.resolve(this.cwd,(0,import_build_utils5.isExperimentalServiceV2)(service)?service.root||".":service.workspace||"."));this.pythonServiceCount=new Set(pythonWorkspaces).size,this.hasQueueServices=options.services.filter(import_build_utils5.isExperimentalService).some(import_build_utils5.isQueueBackedService)}forceKillAllSync(){let killOne=pid=>{if(pid)try{killGroup(pid,"SIGKILL")}catch{}};for(let[,proc]of this.managedProcesses)killOne(proc.pid);for(let[,service]of this.managedServices)killOne(service.pid)}registerExitBackstop(){if(this.exitBackstop)return;let backstop=()=>this.forceKillAllSync();this.exitBackstop=backstop,process.on("exit",backstop)}unregisterExitBackstop(){this.exitBackstop&&(process.removeListener("exit",this.exitBackstop),this.exitBackstop=void 0)}async startAll(){output_manager_default.debug(`Starting ${this.services.length} services`),this.registerExitBackstop(),await this.allocateServicePorts();let startPromises=this.services.map((service,index)=>this.startService(service,index).then(result=>(this.managedServices.set(result.name,result),result))),failures=(await Promise.allSettled(startPromises)).filter(r=>r.status==="rejected");if(failures.length>0)throw await this.stopAll(),new ServiceStartError(failures.map(f=>f.reason));output_manager_default.debug(`All ${this.managedServices.size} services started successfully`),this.startCronSchedulers()}async stopAll(){if(this.stopping)return;this.stopping=!0;let totalCount=this.managedServices.size+this.managedProcesses.size;output_manager_default.debug(`Stopping ${totalCount} services/processes`);let stopPromises=[];for(let[name,service]of this.managedServices){output_manager_default.debug(`Stopping service "${name}" (PID: ${service.pid})`);let stopService=async()=>{service.shutdown&&await service.shutdown().catch(err=>{output_manager_default.debug(`Failed to shutdown service "${name}": ${err}`)}),service.pid&&await this.terminateProcessGroup(name,service.pid,service.process).catch(err=>{output_manager_default.debug(`Failed to kill service "${name}": ${err}`)})};stopPromises.push(stopService()),service.logger.cleanup()}for(let[name,proc]of this.managedProcesses)proc.pid&&!this.managedServices.has(name)&&(output_manager_default.debug(`Stopping process "${name}" (PID: ${proc.pid})`),stopPromises.push(this.terminateProcessGroup(name,proc.pid,proc).catch(err=>{output_manager_default.debug(`Failed to stop process "${name}": ${err}`)})));for(let timer of this.cronTimers)clearTimeout(timer);this.cronTimers=[];let timedOut=!1,timeoutHandle,timeout=new Promise(resolve3=>{timeoutHandle=setTimeout(()=>{timedOut=!0,output_manager_default.debug(`stopAll timed out after ${STOP_ALL_TIMEOUT_MS}ms; remaining processes will be SIGKILLed on exit`),resolve3()},STOP_ALL_TIMEOUT_MS)});try{await Promise.race([Promise.all(stopPromises),timeout])}finally{timeoutHandle&&clearTimeout(timeoutHandle)}timedOut||(this.managedServices.clear(),this.managedProcesses.clear(),this.unregisterExitBackstop(),output_manager_default.debug("All services stopped"))}async terminateProcessGroup(name,pid,proc){try{killGroup(pid,"SIGTERM")}catch(err){output_manager_default.debug(`SIGTERM group kill for "${name}" failed: ${err}`)}if(await treeKill(pid,"SIGTERM").catch(err=>{output_manager_default.debug(`tree-kill (SIGTERM) for "${name}" failed: ${err}`)}),!await waitForExit(pid,proc,FORCE_KILL_GRACE_MS)){output_manager_default.debug(`Escalating to SIGKILL for "${name}" (PID: ${pid})`);try{killGroup(pid,"SIGKILL")}catch(err){output_manager_default.debug(`SIGKILL group kill for "${name}" failed: ${err}`)}await treeKill(pid,"SIGKILL").catch(()=>{})}}getServiceForRoute(pathname){let bestMatch=null,bestMatchLength=-1;for(let service of this.managedServices.values())for(let routePrefix of service.routePrefixes){if(routePrefix==="/"){bestMatchLength===-1&&(bestMatch=service,bestMatchLength=0);continue}let normalizedPrefix=routePrefix.startsWith("/")?routePrefix:`/${routePrefix}`;(pathname===normalizedPrefix||pathname.startsWith(`${normalizedPrefix}/`))&&normalizedPrefix.length>bestMatchLength&&(bestMatch=service,bestMatchLength=normalizedPrefix.length)}return bestMatch}getServiceOrigin(serviceName){let service=this.managedServices.get(serviceName);return service?`http://${service.host}:${service.port}`:null}hasServices(){return this.managedServices.size>0}getServices(){return this.managedServices}async allocateServicePorts(){let used=new Set;for(let service of this.services){let port=await(0,import_get_port.default)();for(;used.has(port);)port=await(0,import_get_port.default)();used.add(port),this.servicePorts.set(service.name,port)}}async startService(service,colorIndex){let logger=createServiceLogger(service.name,colorIndex,this.maxNameLength),spec=(0,import_build_utils5.isExperimentalServiceV2)(service)?this.getV2StartSpec(service):this.getV1StartSpec(service),port=this.servicePorts.get(service.name);port!==void 0&&(spec.env.VERCEL_DEV_PORT=String(port));let buildpackRuntime=getBuildpackRuntime(service.builder);if(buildpackRuntime)throw buildpackServicesDevUnsupportedError([{name:service.name,runtime:buildpackRuntime}]);if(spec.builderSpec){let result=await this.tryStartWithBuilder(service.name,spec,logger,port);if(result)return result}let devCommand2=spec.explicitDevCommand||spec.framework?.settings?.devCommand?.value;if(!devCommand2)throw dev.DEV_SERVICE_NO_DEV_SERVER({name:service.name,framework:service.framework??"none"});return this.spawnDevCommandProcess({name:service.name,devCommand:devCommand2,framework:spec.framework,workspacePath:spec.rootPath,env:spec.env,logger,builderConfig:spec.builderConfig,routePrefixes:spec.routePrefixes,workspaceLabel:spec.rootLabel,port})}applyRuntimeCacheEnv(env){env.RUNTIME_CACHE_ENDPOINT||Object.assign(env,getDevRuntimeCacheEnv(this.resourceEndpoints.runtimeCache.direct,""))}applyContainerResourceProxyEnv(env){let endpoints=this.resourceEndpoints;Object.assign(env,getDevSchedulesEnv(endpoints.schedules?.proxy,!0)),env.VERCEL_QUEUE_BASE_URL===endpoints.queues.direct&&Object.assign(env,getDevQueueEnv(endpoints.queues.proxy,env.VERCEL_HAS_WORKER_SERVICES!==void 0)),env.RUNTIME_CACHE_ENDPOINT===endpoints.runtimeCache.direct&&Object.assign(env,getDevRuntimeCacheEnv(endpoints.runtimeCache.proxy,""))}getV1StartSpec(service){let framework=import_frameworks2.frameworkList.find(f=>f.slug===service.framework),effectiveProcessEnv=(0,import_build_utils5.cloneEnv)(this.envFilesValues,process.env),perServiceEnv={};this.useImplicitEnvInjection?perServiceEnv=(0,import_build_utils5.getExperimentalServiceUrlEnvVars)({services:this.services,frameworkList:framework?[framework]:[],origin:this.proxyOrigin,currentEnv:effectiveProcessEnv}):service.env&&(perServiceEnv=(0,import_build_utils5.getServiceUrlEnvVars)({requestedEnv:service.env,consumerService:service,services:this.services,frameworkList:import_frameworks2.frameworkList,origin:this.proxyOrigin,currentEnv:effectiveProcessEnv}));let env=(0,import_build_utils5.cloneEnv)({FORCE_COLOR:process.stdout.isTTY?"1":"0",BROWSER:"none"},perServiceEnv,effectiveProcessEnv);env.VERCEL_SERVICE_TYPE=service.type,service.trigger&&(env.VERCEL_SERVICE_TRIGGER=service.trigger),this.hasQueueServices&&service.runtime==="python"&&env.VERCEL_HAS_WORKER_SERVICES===void 0&&(env.VERCEL_HAS_WORKER_SERVICES="1"),Object.assign(env,getDevQueueEnv(this.resourceEndpoints.queues.direct,this.hasQueueServices)),this.applyRuntimeCacheEnv(env),Object.assign(env,getDevSchedulesEnv(this.resourceEndpoints.schedules?.direct)),service.routePrefix&&service.routePrefix!=="/"&&(env.VERCEL_SERVICE_ROUTE_PREFIX=service.routePrefix,env.VERCEL_SERVICE_ROUTE_PREFIX_STRIP="1");let workspace=service.workspace||".";return{rootPath:path2.join(this.cwd,workspace),rootLabel:workspace,framework,builderSpec:this.preferServiceBuilder?service.builder?.use||framework?.useRuntime?.use:framework?.useRuntime?.use||service.builder?.use,entrypoint:getEntrypointForService(service.builder?.src,service.entrypoint,workspace),builderConfig:service.builder?.config,frameworkForDev:service.framework||"services",servicePayload:{name:service.name,type:service.type,trigger:service.trigger,routePrefix:service.routePrefix,subdomain:service.subdomain,workspace:service.workspace,schedule:service.schedule},routePrefixes:getServiceRoutePrefixes(service),env}}getV2StartSpec(service){let framework=import_frameworks2.frameworkList.find(f=>f.slug===service.framework),effectiveProcessEnv=(0,import_build_utils5.cloneEnv)(this.envFilesValues,process.env),perServiceEnv={};for(let binding of service.bindings??[]){if(binding.type!==void 0&&binding.type!=="service"||binding.format!=="url"||binding.env in effectiveProcessEnv)continue;let targetPort=this.servicePorts.get(binding.service);targetPort!==void 0&&(perServiceEnv[binding.env]=`http://127.0.0.1:${targetPort}`)}let env=(0,import_build_utils5.cloneEnv)({FORCE_COLOR:process.stdout.isTTY?"1":"0",BROWSER:"none"},effectiveProcessEnv,perServiceEnv);this.hasQueueServices&&service.runtime==="python"&&env.VERCEL_HAS_WORKER_SERVICES===void 0&&(env.VERCEL_HAS_WORKER_SERVICES="1"),Object.assign(env,getDevQueueEnv(this.resourceEndpoints.queues.direct,this.hasQueueServices)),this.applyRuntimeCacheEnv(env),Object.assign(env,getDevSchedulesEnv(this.resourceEndpoints.schedules?.direct));let root=service.root||".";return{rootPath:path2.join(this.cwd,root),rootLabel:root,framework,builderSpec:framework?.useRuntime?.use||service.builder?.use,entrypoint:getEntrypointForService(service.builder?.src,service.entrypoint,root),builderConfig:service.builder?.config,frameworkForDev:service.framework||"services",servicePayload:{name:service.name,workspace:root},routePrefixes:[],env,explicitDevCommand:service.devCommand}}async tryStartWithBuilder(name,spec,logger,port){if(!spec.builderSpec)return null;try{let builderWithPkg=(await importBuilders(new Set([spec.builderSpec]),this.cwd)).get(spec.builderSpec),builder=builderWithPkg?.builder;if(!builder?.startDevServer)return null;builderWithPkg?.pkg.name==="@vercel/container"&&this.applyContainerResourceProxyEnv(spec.env),output_manager_default.debug(`Starting ${import_chalk.default.bold(name)} using ${import_chalk.default.cyan.bold(spec.builderSpec)}`),injectNextDevWebSocketShimIfNeeded(spec.env,spec.framework?.settings.devCommand?.value||"",{framework:spec.framework?.slug});let result=await builder.startDevServer({entrypoint:spec.entrypoint,workPath:spec.rootPath,repoRootPath:this.repoRoot,config:{...spec.builderConfig||{},framework:spec.frameworkForDev},meta:{isDev:!0,env:spec.env,port,serviceCount:this.services.length,pythonServiceCount:this.pythonServiceCount,syncDependencies:!0,serviceName:name,devResourceEndpoints:this.resourceEndpoints},service:spec.servicePayload,files:{},onStdout:data=>logger.stdout.write(data),onStderr:data=>logger.stderr.write(data)});if(!result)return null;let host=await checkForPort(result.port,STARTUP_TIMEOUT);return output_manager_default.debug(`Service ${name} started on ${host}:${result.port}`),result.queueSubscriptions?.length&&this.onQueueSubscriptions?.(name,result.queueSubscriptions),{name,host,port:result.port,pid:result.pid,shutdown:result.shutdown,routePrefixes:spec.routePrefixes,workspace:spec.rootLabel,logger,crons:result.crons,queueSubscriptions:result.queueSubscriptions}}catch(err){if(output_manager_default.debug(`Failed to use startDevServer for ${name}: ${err}`),err instanceof import_build_utils5.NowBuildError)throw err;return null}}async spawnDevCommandProcess(params){let{name,devCommand:devCommand2,framework,workspacePath,env,logger,builderConfig,routePrefixes,workspaceLabel}=params;await this.syncDependencies(builderConfig,workspacePath,logger);let port=params.port??await(0,import_get_port.default)();env.PORT=`${port}`,env.VERCEL_CLI_VERSION=pkg_default.version;let command=replaceDevCommandPort(devCommand2,port),nodeBinPath=(0,import_build_utils5.getNodeBinPaths)({base:this.repoRoot,start:workspacePath}).join(path2.delimiter);env.PATH=`${nodeBinPath}${path2.delimiter}${env.PATH}`,output_manager_default.debug(`Starting ${import_chalk.default.bold(name)} with ${import_chalk.default.cyan.bold(`"${command}"`)}`),process.stdout.columns&&(env.COLUMNS=`${process.stdout.columns}`),injectNextDevWebSocketShimIfNeeded(env,command,{framework:framework?.slug});let child=(0,import_build_utils5.spawnCommand)(command,{cwd:workspacePath,env,stdio:["ignore","pipe","pipe"],detached:!0});if(child.pid){if(!child.stdout||!child.stderr)throw dev.DEV_SERVICE_NO_STDIO({name})}else throw dev.DEV_SERVICE_NO_PID({name});this.managedProcesses.set(name,child),child.stdout?.on("data",chunk=>{logger.stdout.write(chunk)}),child.stderr?.on("data",chunk=>{logger.stderr.write(chunk)});let host;try{host=await this.waitForPort(child,name,port)}catch(error2){throw this.managedProcesses.delete(name),error2}return output_manager_default.debug(`Service ${name} listening on ${host}:${port}`),{name,host,port,pid:child.pid,process:child,routePrefixes,workspace:workspaceLabel,logger}}async waitForPort(child,serviceName,port){let processError=new Promise((_,reject)=>{child.on("error",reject),child.on("exit",code=>{reject(new Error(`Service "${serviceName}" exited with code ${code} before port was available`))})});return Promise.race([checkForPort(port,STARTUP_TIMEOUT),processError])}async syncDependencies(config,workspacePath,logger){logger.stdout.write(`${import_chalk.default.gray("Synchronizing dependencies...")}
41
- `);let installCommand=typeof config?.installCommand=="string"?config.installCommand.trim():"";installCommand?await this.runInstallCommand(installCommand,workspacePath,logger):await this.maybeInstallJSDependencies(workspacePath,logger)}async runBuffered(logger,task){let captured=[],bufStdout=new Writable({write(chunk,_enc,cb){let b=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);captured.push(["stdout",b]),output_manager_default.debugEnabled&&logger.stdout.write(b),cb()}}),bufStderr=new Writable({write(chunk,_enc,cb){let b=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);captured.push(["stderr",b]),output_manager_default.debugEnabled&&logger.stderr.write(b),cb()}});try{await task(bufStdout,bufStderr)}catch(err){for(let[channel,chunk]of captured)logger[channel].write(chunk);throw err}}async runInstallCommand(command,workspacePath,logger){await this.runBuffered(logger,(stdout,stderr)=>new Promise((resolve3,reject)=>{output_manager_default.debug(`Running install command: "${command}" in ${workspacePath}`);let child=(0,import_build_utils5.spawnCommand)(command,{cwd:workspacePath,stdio:["inherit","pipe","pipe"]});child.stdout?.on("data",chunk=>stdout.write(chunk)),child.stderr?.on("data",chunk=>stderr.write(chunk)),child.on("error",reject),child.on("exit",(code,signal)=>{code===0?resolve3():reject(new import_build_utils5.NowBuildError({code:"INSTALL_COMMAND_FAILED",message:`Install command "${command}" failed with code ${code}, signal ${signal}`}))})}))}async maybeInstallJSDependencies(workspacePath,logger){await this.runBuffered(logger,async(stdout,stderr)=>{try{await(0,import_build_utils5.runNpmInstall)(workspacePath,[],void 0,this.installMeta,void 0,{stdout,stderr})}catch(err){throw new import_build_utils5.NowBuildError({code:"NODE_DEPENDENCY_SYNC_FAILED",message:`Failed to install Node.JS dependencies: ${err instanceof Error?err.message:String(err)}`})}})}startCronSchedulers(){for(let[name,managed]of this.managedServices){let service=this.services.find(candidate=>candidate.name===name),crons=managed.crons&&managed.crons.length>0?managed.crons:service&&(0,import_build_utils5.isExperimentalService)(service)&&(0,import_build_utils5.isScheduleTriggeredService)(service)&&service.schedule?(0,import_service_schedules.getStaticServiceSchedules)(service.schedule).map(schedule=>({path:(0,import_build_utils5.getInternalServiceCronPath)(name,service.entrypoint||service.builder.src||"index",service.handlerFunction||"cron"),schedule})):[];if(crons.length!==0)for(let cron of crons)output_manager_default.debug(`Scheduling job service ${import_chalk.default.bold(name)} (${import_chalk.default.cyan(cron.schedule)})`),this.scheduleCronTrigger(name,cron.path,cron.schedule,managed)}}scheduleCronTrigger(serviceName,cronPath,schedule,managed){let delayMs=getNextCronDelay(schedule);if(delayMs===null){output_manager_default.warn(`Could not parse cron schedule "${schedule}" for service "${serviceName}", skipping auto-trigger`);return}let timer=setTimeout(async()=>{if(!this.stopping){output_manager_default.debug(`Triggering scheduled job ${import_chalk.default.bold(serviceName)} (schedule: ${import_chalk.default.cyan(schedule)})`);try{let url4=`http://${managed.host}:${managed.port}${cronPath}`,res=await fetch(url4,{method:"POST"});output_manager_default.debug(`Cron trigger for "${serviceName}" responded with status ${res.status}`)}catch(err){output_manager_default.error(`Cron trigger for "${serviceName}" failed: ${err instanceof Error?err.message:String(err)}`)}this.scheduleCronTrigger(serviceName,cronPath,schedule,managed)}},delayMs);this.cronTimers.push(timer)}};var import_ms5=__toESM(require_ms(),1);import{randomBytes}from"crypto";var import_build_utils6=__toESM(require_build_utils(),1);var DEFAULT_RETRY_AFTER=(0,import_ms5.default)("1m"),DEFAULT_MAX_DELIVERIES=32,DEFAULT_INITIAL_DELAY=0,DEFAULT_VISIBILITY_TIMEOUT=(0,import_ms5.default)("1m"),DEFAULT_RETENTION=(0,import_ms5.default)("1h"),TICK_INTERVAL2=(0,import_ms5.default)("1s");function topicPatternToRegex(pattern){let parts=pattern.split("*").map(s=>s.replace(/-/g,"\\-"));return new RegExp(`^${parts.join("[A-Za-z0-9_\\-]*")}$`)}var QueueBroker=class{constructor(services,getServiceOrigin){this.getServiceOrigin=getServiceOrigin;this.messages=new Map;this.idempotencyRecords=new Map;this.duplicateMessages=new Map;this.consumerGroups=[];this.deliveryState=new Map;this.registerServices(services),this.tickTimer=setInterval(()=>this.tick(),TICK_INTERVAL2),this.tickTimer.unref()}registerServices(services){let ids=new Set;for(let service of services.filter(import_build_utils6.isQueueBackedService))for(let{topic}of(0,import_build_utils6.getServiceQueueTopicConfigs)(service)){let consumerGroup=service.consumer??service.name,id=`${consumerGroup}::${topic}`,existing=this.consumerGroups.find(group=>group.id===id);if(ids.has(id)||existing?.serviceOriginFn||existing?.resolveFunction)throw dev.DEV_QUEUE_CONSUMER_DUPLICATE({consumerGroup,topic});ids.add(id)}for(let service of services){if(!(0,import_build_utils6.isQueueBackedService)(service))continue;let topicConfigs=(0,import_build_utils6.getServiceQueueTopicConfigs)(service),consumerGroup=service.consumer??service.name;for(let topicConfig of topicConfigs){let topicPattern=topicConfig.topic,id=`${consumerGroup}::${topicPattern}`,existingGroup=this.consumerGroups.find(group2=>group2.id===id);if(existingGroup&&!existingGroup.serviceOriginFn&&!existingGroup.resolveFunction){existingGroup.serviceName=service.name,existingGroup.serviceOriginFn=()=>this.getServiceOrigin(service.name),existingGroup.retryAfterMs=topicConfig.retryAfterSeconds!==void 0?topicConfig.retryAfterSeconds*1e3:DEFAULT_RETRY_AFTER,existingGroup.initialDelayMs=topicConfig.initialDelaySeconds!==void 0?topicConfig.initialDelaySeconds*1e3:DEFAULT_INITIAL_DELAY,this.activatePushGroup(existingGroup);continue}if(existingGroup)throw dev.DEV_QUEUE_CONSUMER_DUPLICATE({consumerGroup,topic:topicPattern});let group={id,name:consumerGroup,serviceName:service.name,topicPattern,topicRegex:topicPatternToRegex(topicPattern),serviceOriginFn:()=>this.getServiceOrigin(service.name),retryAfterMs:topicConfig.retryAfterSeconds!==void 0?topicConfig.retryAfterSeconds*1e3:DEFAULT_RETRY_AFTER,maxDeliveries:DEFAULT_MAX_DELIVERIES,initialDelayMs:topicConfig.initialDelaySeconds!==void 0?topicConfig.initialDelaySeconds*1e3:DEFAULT_INITIAL_DELAY};this.consumerGroups.push(group),this.deliveryState.set(group.id,this.createRetainedDeliveries(group)),this.activatePushGroup(group)}}}updateServiceSubscriptions(serviceName,subscriptions){if(subscriptions.length===0)return;let kept=[];for(let group of this.consumerGroups)group.serviceName===serviceName?this.deliveryState.delete(group.id):kept.push(group);this.consumerGroups=kept;for(let subscription of subscriptions){let id=`${subscription.consumer}::${subscription.topic}`,existingGroup=this.consumerGroups.find(group2=>group2.id===id);if(existingGroup&&!existingGroup.serviceOriginFn&&!existingGroup.resolveFunction){existingGroup.serviceName=serviceName,existingGroup.serviceOriginFn=()=>this.getServiceOrigin(serviceName),existingGroup.retryAfterMs=subscription.retryAfterSeconds!==void 0?subscription.retryAfterSeconds*1e3:DEFAULT_RETRY_AFTER,existingGroup.maxDeliveries=subscription.maxDeliveries??DEFAULT_MAX_DELIVERIES,existingGroup.initialDelayMs=subscription.initialDelaySeconds!==void 0?subscription.initialDelaySeconds*1e3:DEFAULT_INITIAL_DELAY,this.activatePushGroup(existingGroup);continue}if(existingGroup){output_manager_default.debug(`Queue consumer "${subscription.consumer}" is already registered for topic "${subscription.topic}"; keeping the first registration`);continue}let group={id,name:subscription.consumer,serviceName,topicPattern:subscription.topic,topicRegex:topicPatternToRegex(subscription.topic),serviceOriginFn:()=>this.getServiceOrigin(serviceName),retryAfterMs:subscription.retryAfterSeconds!==void 0?subscription.retryAfterSeconds*1e3:DEFAULT_RETRY_AFTER,maxDeliveries:subscription.maxDeliveries??DEFAULT_MAX_DELIVERIES,initialDelayMs:subscription.initialDelaySeconds!==void 0?subscription.initialDelaySeconds*1e3:DEFAULT_INITIAL_DELAY};this.consumerGroups.push(group),this.deliveryState.set(group.id,this.createRetainedDeliveries(group)),this.activatePushGroup(group)}output_manager_default.debug(`Queue consumer groups for service "${serviceName}" updated from ${subscriptions.length} introspected subscription(s)`)}validateFunctionSubscriptions(subscriptions){let ids=new Set;for(let subscription of subscriptions){let id=`${subscription.consumer}::${subscription.topic}`,existing=this.consumerGroups.find(group=>group.id===id);if(ids.has(id)||existing?.serviceOriginFn&&!existing.configOwned)throw dev.DEV_QUEUE_CONSUMER_DUPLICATE({consumerGroup:subscription.consumer,topic:subscription.topic});ids.add(id)}}setFunctionSubscriptions(subscriptions,resolve3){this.validateFunctionSubscriptions(subscriptions);let ids=new Set(subscriptions.map(subscription=>`${subscription.consumer}::${subscription.topic}`));for(let group of this.consumerGroups)group.configOwned&&!ids.has(group.id)&&(delete group.configOwned,delete group.resolveFunction);for(let subscription of subscriptions){let id=`${subscription.consumer}::${subscription.topic}`,group=this.consumerGroups.find(group2=>group2.id===id);group||(group={id,name:subscription.consumer,topicPattern:subscription.topic,topicRegex:topicPatternToRegex(subscription.topic),retryAfterMs:DEFAULT_RETRY_AFTER,maxDeliveries:DEFAULT_MAX_DELIVERIES,initialDelayMs:DEFAULT_INITIAL_DELAY},this.consumerGroups.push(group),this.deliveryState.set(id,this.createRetainedDeliveries(group))),group.configOwned=!0,group.resolveFunction=()=>resolve3(subscription.outputPath),group.retryAfterMs=subscription.retryAfterSeconds===void 0?DEFAULT_RETRY_AFTER:subscription.retryAfterSeconds*1e3,group.maxDeliveries=subscription.maxDeliveries??DEFAULT_MAX_DELIVERIES,group.initialDelayMs=(subscription.initialDelaySeconds??0)*1e3,this.activatePushGroup(group)}}enqueue(queueName,payload,contentType2,options){let now=Date.now(),messageId=randomBytes(16).toString("hex"),retentionMs=(options?.retentionSeconds??0)>0?options.retentionSeconds*1e3:DEFAULT_RETENTION,idempotencyRecordKey=options?.idempotencyKey?`${queueName}:${options.idempotencyKey}`:void 0;if(idempotencyRecordKey){let record=this.idempotencyRecords.get(idempotencyRecordKey);if(record&&record.expiresAt>Date.now())return this.duplicateMessages.set(messageId,{queueName,originalMessageId:record.messageId,expiresAt:Date.now()+retentionMs}),output_manager_default.debug(`queues: skipped duplicate message for queue "${queueName}"`),{messageId};record&&this.idempotencyRecords.delete(idempotencyRecordKey)}idempotencyRecordKey&&this.idempotencyRecords.set(idempotencyRecordKey,{messageId,expiresAt:Date.now()+retentionMs});let message2={messageId,payload,contentType:contentType2,queueName,createdAt:new Date(now).toISOString(),retentionMs,visibleAt:(options?.delaySeconds??0)>0?now+options.delaySeconds*1e3:0};this.messages.set(messageId,message2),output_manager_default.debug(`queues: stored message ${messageId} for queue "${queueName}"`);let matchingGroups=this.consumerGroups.filter(g=>g.topicRegex.test(queueName));matchingGroups.length===0&&output_manager_default.debug(`queues: no consumer group matches topic "${queueName}", message stored but not dispatched`);for(let group of matchingGroups){let groupDeliveries=this.deliveryState.get(group.id),initialVisibleAt=group.initialDelayMs>0?now+group.initialDelayMs:0,visibleAt=Math.max(message2.visibleAt,initialVisibleAt);groupDeliveries.set(messageId,{status:"pending",deliveryCount:0,receiptHandle:"",visibleAt,leaseExpiresAt:0}),visibleAt<=now&&(group.serviceOriginFn||group.resolveFunction)&&this.dispatchToConsumer(message2,group).catch(err=>{output_manager_default.debug(`queues: unexpected dispatch error: ${err}`)})}return{messageId}}getOriginalMessageIdForDuplicate(queueName,messageId){let duplicate=this.duplicateMessages.get(messageId);return!duplicate||duplicate.queueName!==queueName?null:duplicate.expiresAt<=Date.now()?(this.duplicateMessages.delete(messageId),null):duplicate.originalMessageId}receiveById(queueName,messageId,consumerGroup){let message2=this.messages.get(messageId);if(!message2||message2.queueName!==queueName||this.isMessageExpired(message2))return null;let group=this.getOrCreatePullGroup(queueName,consumerGroup),state=this.deliveryState.get(group.id)?.get(messageId);if(!state)return null;if(state.status==="pending"){if(state.visibleAt>Date.now())return null;state.status="in-flight",state.receiptHandle=randomBytes(16).toString("hex"),state.deliveryCount++,state.leaseExpiresAt=Date.now()+DEFAULT_VISIBILITY_TIMEOUT}return{messageId:message2.messageId,payload:message2.payload,contentType:message2.contentType,deliveryCount:state.deliveryCount,createdAt:message2.createdAt,receiptHandle:state.receiptHandle}}receiveMessages(queueName,consumerGroup,options){let group=this.getOrCreatePullGroup(queueName,consumerGroup),groupDeliveries=this.deliveryState.get(group.id);if(!groupDeliveries)return[];let now=Date.now(),limit=Math.min(Math.max(options?.limit??1,1),10),visibilityTimeoutMs=(options?.visibilityTimeoutSeconds??DEFAULT_VISIBILITY_TIMEOUT/1e3)*1e3,results=[];for(let[messageId,state]of groupDeliveries){let message2=this.messages.get(messageId);if(!message2){groupDeliveries.delete(messageId);continue}if(this.isMessageExpired(message2,now)){this.deleteMessage(messageId);continue}if(message2.queueName!==queueName||state.status!=="pending"||state.visibleAt>now)continue;let receiptHandle=randomBytes(16).toString("hex");if(state.status="in-flight",state.receiptHandle=receiptHandle,state.deliveryCount++,state.leaseExpiresAt=Date.now()+visibilityTimeoutMs,results.push({messageId:message2.messageId,payload:message2.payload,contentType:message2.contentType,deliveryCount:state.deliveryCount,createdAt:message2.createdAt,receiptHandle}),results.length>=limit)break}return results}acknowledge(messageId,consumerGroup,receiptHandle){let{deliveries:groupDeliveries,state}=this.findDeliveryState(messageId,consumerGroup);return!groupDeliveries||!state?!1:state.receiptHandle&&state.receiptHandle!==receiptHandle?(output_manager_default.debug(`queues: ACK rejected for ${messageId} in group "${consumerGroup}" - receipt handle mismatch`),!1):(state.status="acked",groupDeliveries.delete(messageId),output_manager_default.debug(`queues: ACK message ${messageId} in group "${consumerGroup}"`),!0)}changeVisibility(messageId,consumerGroup,receiptHandle,timeoutSeconds){let{state}=this.findDeliveryState(messageId,consumerGroup);return!state||state.status!=="in-flight"||state.receiptHandle&&state.receiptHandle!==receiptHandle?!1:(state.leaseExpiresAt=Date.now()+timeoutSeconds*1e3,output_manager_default.debug(`queues: visibility for ${messageId} in group "${consumerGroup}" extended by ${timeoutSeconds}s`),!0)}findMessageIdByReceiptHandle(consumerGroup,receiptHandle){for(let group of this.consumerGroups){if(group.name!==consumerGroup)continue;let deliveries=this.deliveryState.get(group.id);if(deliveries){for(let[messageId,state]of deliveries)if(state.receiptHandle===receiptHandle)return messageId}}return null}findDeliveryState(messageId,serviceName){for(let group of this.consumerGroups){if(group.name!==serviceName)continue;let deliveries=this.deliveryState.get(group.id);if(!deliveries)continue;let state=deliveries.get(messageId);if(state)return{deliveries,state}}return{deliveries:null,state:null}}getOrCreatePullGroup(queueName,consumerGroup){let existingGroup=this.consumerGroups.find(group2=>group2.name===consumerGroup&&group2.topicRegex.test(queueName));if(existingGroup)return existingGroup;let group={id:`${consumerGroup}::${queueName}`,name:consumerGroup,topicPattern:queueName,topicRegex:topicPatternToRegex(queueName),retryAfterMs:DEFAULT_RETRY_AFTER,maxDeliveries:DEFAULT_MAX_DELIVERIES,initialDelayMs:DEFAULT_INITIAL_DELAY},deliveries=new Map;for(let message2 of this.messages.values())message2.queueName!==queueName||this.isMessageExpired(message2)||deliveries.set(message2.messageId,{status:"pending",deliveryCount:0,receiptHandle:"",visibleAt:message2.visibleAt,leaseExpiresAt:0});return this.consumerGroups.push(group),this.deliveryState.set(group.id,deliveries),group}isMessageExpired(message2,now=Date.now()){return new Date(message2.createdAt).getTime()+message2.retentionMs<now}deleteMessage(messageId){this.messages.delete(messageId);for(let groupDeliveries of this.deliveryState.values())groupDeliveries.delete(messageId)}createRetainedDeliveries(group){let deliveries=new Map;for(let message2 of this.messages.values())!group.topicRegex.test(message2.queueName)||this.isMessageExpired(message2)||deliveries.set(message2.messageId,{status:"pending",deliveryCount:0,receiptHandle:"",visibleAt:Math.max(message2.visibleAt,new Date(message2.createdAt).getTime()+group.initialDelayMs),leaseExpiresAt:0});return deliveries}activatePushGroup(group){if(!group.serviceOriginFn&&!group.resolveFunction)return;let now=Date.now(),deliveries=this.deliveryState.get(group.id);if(deliveries)for(let[messageId,state]of deliveries){let message2=this.messages.get(messageId);!message2||state.status!=="pending"||(state.visibleAt=Math.max(state.visibleAt,new Date(message2.createdAt).getTime()+group.initialDelayMs),state.visibleAt<=now&&this.dispatchToConsumer(message2,group).catch(err=>{output_manager_default.debug(`queues: unexpected dispatch error: ${err}`)}))}}async dispatchToConsumer(message2,group){let groupDeliveries=this.deliveryState.get(group.id);if(!groupDeliveries)return;let state=groupDeliveries.get(message2.messageId);if(!state||state.status!=="pending")return;if(state.deliveryCount>=group.maxDeliveries){output_manager_default.debug(`queues: message ${message2.messageId} exceeded maxDeliveries (${group.maxDeliveries}) for group "${group.name}", dropping`),groupDeliveries.delete(message2.messageId);return}let upstream=group.serviceOriginFn?.(),dispatch=group.resolveFunction?.();if(!upstream&&!dispatch){state.visibleAt=Date.now()+TICK_INTERVAL2;return}let receiptHandle=randomBytes(16).toString("hex");state.status="in-flight",state.receiptHandle=receiptHandle,state.deliveryCount++,state.leaseExpiresAt=Date.now()+DEFAULT_VISIBILITY_TIMEOUT;let now=new Date().toISOString(),expiresAt=new Date(new Date(message2.createdAt).getTime()+message2.retentionMs).toISOString();output_manager_default.debug(`queues: dispatching v2beta callback to worker "${group.name}"`);try{let request={method:"POST",headers:{"content-type":message2.contentType,"ce-type":"com.vercel.queue.v2beta","ce-specversion":"1.0","ce-source":`/topic/${message2.queueName}/consumer/${group.name}`,"ce-id":message2.messageId,"ce-time":now,"ce-vqsmessageid":message2.messageId,"ce-vqsqueuename":message2.queueName,"ce-vqsconsumergroup":group.name,"ce-vqsreceipthandle":receiptHandle,"ce-vqsdeliverycount":String(state.deliveryCount),"ce-vqscreatedat":message2.createdAt,"ce-vqsexpiresat":expiresAt,"ce-vqsregion":"dev1"},body:message2.payload},response=dispatch?await dispatch(request):await directFetch(`${upstream}/`,request);if(response===null){state.receiptHandle===receiptHandle&&state.status==="in-flight"&&(state.status="pending",state.deliveryCount--,state.receiptHandle="",state.leaseExpiresAt=0,state.visibleAt=Date.now()+TICK_INTERVAL2);return}response.ok||(output_manager_default.debug(`queues: worker "${group.name}" returned ${response.status} for message ${message2.messageId}`),this.handleDeliveryFailure(message2.messageId,group,receiptHandle))}catch(err){output_manager_default.debug(`queues: failed to dispatch CloudEvent to "${group.name}": ${err}`),this.handleDeliveryFailure(message2.messageId,group,receiptHandle)}}handleDeliveryFailure(messageId,group,receiptHandle){let groupDeliveries=this.deliveryState.get(group.id);if(!groupDeliveries)return;let state=groupDeliveries.get(messageId);!state||state.receiptHandle!==receiptHandle||(state.status="pending",state.visibleAt=Date.now()+group.retryAfterMs,state.leaseExpiresAt=0)}tick(){let now=Date.now();for(let[key,record]of this.idempotencyRecords)record.expiresAt<=now&&this.idempotencyRecords.delete(key);for(let[messageId,record]of this.duplicateMessages)record.expiresAt<=now&&this.duplicateMessages.delete(messageId);for(let[messageId,message2]of this.messages)this.isMessageExpired(message2,now)&&this.deleteMessage(messageId);for(let group of this.consumerGroups){let groupDeliveries=this.deliveryState.get(group.id);if(groupDeliveries)for(let[messageId,state]of groupDeliveries){let message2=this.messages.get(messageId);if(!message2){groupDeliveries.delete(messageId);continue}if(state.status==="in-flight"&&state.leaseExpiresAt<=now){state.deliveryCount>=group.maxDeliveries?(output_manager_default.debug(`queues: message ${messageId} exceeded maxDeliveries (${group.maxDeliveries}) for group "${group.name}", dropping`),groupDeliveries.delete(messageId)):(state.status="pending",state.visibleAt=group.serviceOriginFn||group.resolveFunction?now+group.retryAfterMs:now,state.leaseExpiresAt=0);continue}state.status==="pending"&&state.visibleAt<=now&&(group.serviceOriginFn||group.resolveFunction)&&this.dispatchToConsumer(message2,group).catch(err=>{output_manager_default.debug(`queues: unexpected dispatch error: ${err}`)})}}}stop(){clearInterval(this.tickTimer)}};var import_build_utils7=__toESM(require_build_utils(),1),import_minimatch2=__toESM(require_minimatch(),1);import{posix}from"path";function validPath(value,http2=!1){if(typeof value!="string"||!value)return!1;try{let pathname=http2?value:`/${value}`,decoded=decodeURIComponent(pathname);return pathname.startsWith("/")&&!pathname.startsWith("//")&&!/[\\?#\s]/.test(pathname)&&new URL(pathname,"http://localhost").pathname===pathname&&!/[\\?#\x00-\x1f\x7f]/.test(decoded)&&!/%2f/i.test(pathname)&&!decoded.split("/").some(segment=>segment==="."||segment==="..")&&(http2||!value.endsWith("/")&&!value.includes("//"))}catch{return!1}}async function collectDevFunctions({scopes,workPath,files,config,env}){let builders=await importBuilders(new Set(scopes.map(({build})=>build.use)),workPath),unmatched=new Set(Object.entries(config.functions??{}).filter(([,fn2])=>fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta")).map(([pattern])=>pattern)),functions=new Map,schedules=[];for(let scope of scopes){let{build,target}=scope,builder=builders.get(build.use)?.builder;if(!builder)throw dev.DEV_BUILDER_LOAD_FAILED({use:build.use});let scopedConfig=structuredClone({...config,...build.config,functions:build.config?.functions??(build.config?.zeroConfig?{}:config.functions)}),manifest,{scheduleFunction}=build.config??{};if(scheduleFunction&&build.src)manifest={functions:[{outputPath:scheduleFunction.outputPath,sourceFile:build.src,invocation:{type:"entrypoint",entrypoint:build.src},experimentalTriggers:[{type:"schedule/v1beta"}]}],matchedFunctionPatterns:[]};else if(builder.getDevManifest)manifest=await builder.getDevManifest({workPath,build,files,config:scopedConfig,env});else{manifest={functions:[],matchedFunctionPatterns:[]};let mode=build.config??{};if(target!=="builder"||mode.framework||mode.middleware||mode.buildType==="middleware"||mode.buildType==="app"||mode.serviceName||mode.serviceType||mode.buildpack||!build.src||build.src.includes("<"))continue;let pattern=build.src.replace(/^\//,"");for(let sourceFile of files){if(!(sourceFile===pattern||(0,import_minimatch2.default)(sourceFile,pattern,{dot:!0}))||builder.version!==3&&!(builder.version===-1&&mode.zeroConfig&&pattern.startsWith("api/")&&sourceFile.startsWith("api/"))||/(^|\/)package\.json$/.test(sourceFile)||/^(?:src\/)?middleware\.[^/]+$/.test(sourceFile))continue;let extension=posix.extname(sourceFile),outputPath=mode.zeroConfig&&extension?sourceFile.slice(0,-extension.length):sourceFile,{experimentalTriggers}=await(0,import_build_utils7.getLambdaOptionsFromFunction)({sourceFile,config:scopedConfig});manifest.functions.push({outputPath,sourceFile,invocation:{type:"entrypoint",entrypoint:sourceFile},experimentalTriggers});let matched=Object.keys(scopedConfig.functions??{}).find(key=>sourceFile===key||(0,import_minimatch2.default)(sourceFile,key));matched&&manifest.matchedFunctionPatterns.push(matched)}}if(!Array.isArray(manifest?.functions)||!Array.isArray(manifest?.matchedFunctionPatterns)||manifest.matchedFunctionPatterns.some(pattern=>typeof pattern!="string"))throw dev.DEV_FUNCTION_MANIFEST_INVALID({use:build.use});let scheduleError=validateConfig({schedules:manifest.schedules});if(scheduleError)throw scheduleError;for(let fn2 of manifest.functions){if(!validPath(fn2?.outputPath)||fn2.outputPath.endsWith(".func")||fn2.sourceFile!==void 0&&!validPath(fn2.sourceFile)||!fn2.invocation||(fn2.invocation.type==="http"?!validPath(fn2.invocation.pathname,!0):fn2.invocation.type!=="entrypoint"||!validPath(fn2.invocation.entrypoint))||fn2.experimentalTriggers!==void 0&&!Array.isArray(fn2.experimentalTriggers))throw dev.DEV_FUNCTION_MANIFEST_INVALID({use:build.use});if(functions.has(fn2.outputPath))throw dev.DEV_FUNCTION_OUTPUT_DUPLICATE({outputPath:fn2.outputPath});functions.set(fn2.outputPath,{outputPath:fn2.outputPath,sourceFile:fn2.sourceFile,invocation:structuredClone(fn2.invocation),experimentalTriggers:structuredClone(fn2.experimentalTriggers),scope})}schedules.push(...structuredClone(manifest.schedules??[]));for(let pattern of manifest.matchedFunctionPatterns)unmatched.delete(pattern)}return{functions,schedules,unmatchedPatterns:[...unmatched]}}function deriveQueueSubscriptions(registry){let subscriptions=[],ids=new Set;for(let fn2 of registry.functions.values())for(let trigger of fn2.experimentalTriggers??[]){if(!trigger||typeof trigger.type!="string")throw dev.DEV_FUNCTION_MANIFEST_INVALID({use:fn2.scope.build.use});if(trigger.type!=="queue/v2beta")continue;let{consumer,topic,retryAfterSeconds,initialDelaySeconds,maxDeliveries}=trigger;if(typeof consumer!="string"||!consumer||typeof topic!="string"||!topic||[retryAfterSeconds,initialDelaySeconds,maxDeliveries].some(value=>value!==void 0&&(!Number.isFinite(value)||value<0))||retryAfterSeconds!==void 0&&retryAfterSeconds<=0||maxDeliveries!==void 0&&(!Number.isInteger(maxDeliveries)||maxDeliveries<1))throw dev.DEV_FUNCTION_MANIFEST_INVALID({use:fn2.scope.build.use});let id=`${consumer}::${topic}`;if(ids.has(id))throw dev.DEV_QUEUE_CONSUMER_DUPLICATE({consumerGroup:consumer,topic});ids.add(id),subscriptions.push({outputPath:fn2.outputPath,consumer,topic,retryAfterSeconds,initialDelaySeconds,maxDeliveries})}return subscriptions}var import_raw_body=__toESM(require_raw_body(),1),import_local_schedules=__toESM(require_dist9(),1);import{z}from"zod";var identifier=z.string().min(1).max(256).regex(/^[0-9A-Za-z._-]+$/),definition=z.strictObject({expression:z.discriminatedUnion("type",[z.strictObject({type:z.literal("cron"),cron:z.string().min(1)}),z.strictObject({type:z.literal("single"),at:z.string().min(1)})]),timezone:z.string().min(1).max(50).optional(),jitter:z.number().int().min(1).max(15).optional(),target:z.strictObject({type:z.literal("queue"),topic:z.string().regex(/^[A-Za-z0-9_-]+$/)}),payload:z.unknown().optional()}),createBody=definition.extend({name:identifier.optional(),namespace:identifier.optional()}),updateBody=definition.partial().extend({jitter:definition.shape.jitter.nullable()}),scopeQuery=z.object({projectId:z.string().min(1).optional()}),identifierQuery=scopeQuery.extend({namespace:identifier.optional()}),listQuery=identifierQuery.extend({cursor:z.string().min(1).optional(),limit:z.coerce.number().int().min(1).max(100).default(20)}),MAX_PAYLOAD_BYTES=256*1024,MAX_BODY_BYTES=MAX_PAYLOAD_BYTES+16*1024;async function handleSchedulesRequest(broker,projectId,req,res,pathname){let send=(status,data)=>{res.writeHead(status,{"Content-Type":"application/json"}),res.end(JSON.stringify(data))},error2=(status,code,message2)=>send(status,{error:{code,message:message2}});try{let route=/^\/v1\/schedules(?:\/([^/]+)(?:\/(enable|disable|invoke))?)?$/.exec(pathname);if(!route){error2(404,"not_found","Schedule route not found");return}let[,encodedName,action]=route,methods=action?["POST"]:encodedName?["GET","PATCH","DELETE"]:["GET","POST"];if(!methods.includes(req.method||"")){res.setHeader("Allow",methods.join(", ")),error2(405,"method_not_allowed","Method not allowed");return}let query=Object.fromEntries(new URL(req.url||"/","http://localhost").searchParams),parsedQuery=(!encodedName&&req.method==="POST"?scopeQuery:identifierQuery).parse(query);if(parsedQuery.projectId!==void 0&&parsedQuery.projectId!==projectId)throw new import_local_schedules.ScheduleBrokerError("invalid_request","The projectId query parameter must match the local project.");if(!encodedName&&req.method==="GET"){let{namespace,cursor,limit}=listQuery.parse(query);send(200,broker.list({namespace,cursor,limit}));return}if(req.method==="PATCH"||!encodedName&&req.method==="POST"){let body;try{body=JSON.parse(await(0,import_raw_body.default)(req,{limit:MAX_BODY_BYTES,encoding:"utf8"}))}catch(err){let tooLarge=err.statusCode===413;error2(tooLarge?413:400,tooLarge?"payload_too_large":"bad_request",tooLarge?`Schedule request exceeds ${MAX_BODY_BYTES} bytes`:"Expected a JSON object as the request body");return}let parsed=(req.method==="PATCH"?updateBody:createBody).parse(body);if(parsed.payload!==void 0&&Buffer.byteLength(JSON.stringify(parsed.payload))>MAX_PAYLOAD_BYTES){error2(400,"payload_too_large",`Schedule payload exceeds ${MAX_PAYLOAD_BYTES} bytes`);return}encodedName?send(200,broker.update({name:identifier.parse(decodeURIComponent(encodedName)),namespace:identifierQuery.parse(query).namespace},parsed)):send(201,broker.create(createBody.parse(parsed)));return}let id={name:identifier.parse(decodeURIComponent(encodedName)),namespace:identifierQuery.parse(query).namespace};action==="invoke"?(await broker.invoke(id),res.writeHead(204),res.end()):action==="enable"||action==="disable"?send(200,broker[action](id)):req.method==="DELETE"?send(200,broker.delete(id)):send(200,broker.get(id))}catch(err){if(err instanceof z.ZodError)error2(400,"bad_request",err.issues.map(issue=>`${issue.path.join(".")||"request"}: ${issue.message}`).join("; "));else if(err instanceof URIError)error2(400,"bad_request","Invalid encoded schedule name");else if(err instanceof import_local_schedules.ScheduleBrokerError){let status={invalid_request:400,not_found:404,conflict:409,closed:503}[err.code],code={invalid_request:"bad_request",conflict:"schedule_already_exists",closed:"unavailable",not_found:"not_found"}[err.code];error2(status,code,err.message)}else error2(500,"schedule_dispatch_failed",err instanceof Error?err.message:"Failed to dispatch schedule")}}var import_build_utils8=__toESM(require_build_utils(),1);function collectStaticSchedules(authored,registry){let authoredAndNative=[...authored??[],...registry.schedules],error2=validateConfig({schedules:authoredAndNative});if(error2)throw error2;let schedules=authoredAndNative.map(import_build_utils8.parseScheduleDefinition);for(let{name,target}of registry.schedules)if("entrypoint"in target)throw new import_build_utils8.NowBuildError({code:"DEV_SCHEDULE_MANIFEST_ENTRYPOINT",message:`Native schedule "${name}" has an unresolved target.entrypoint. The builder's getDevManifest must return a Build Output API target.function or target.topic instead.`});return schedules.sort((a,b)=>a.name.localeCompare(b.name)),schedules.map(({name,expression,timezone,target})=>{if("entrypoint"in target)throw new import_build_utils8.NowBuildError({code:"DEV_SCHEDULE_ENTRYPOINT_UNSUPPORTED",message:`Schedule "${name}" targets entrypoint "${target.entrypoint}", which vercel dev cannot resolve in a services project yet. Use target.function with an exact registered build output ID and a sole schedule/v1beta trigger, or target.topic for a queue.`});if("function"in target){let fn2=registry.functions.get(target.function);if(!fn2)throw dev.DEV_SCHEDULE_FUNCTION_MISSING({name,outputPath:target.function});if(fn2.experimentalTriggers?.length!==1||fn2.experimentalTriggers[0]?.type!=="schedule/v1beta")throw dev.DEV_SCHEDULE_FUNCTION_TRIGGER({name,outputPath:target.function})}return{name,expression:{type:"cron",cron:expression.cron},jitter:expression.jitter,timezone,target:"function"in target?{type:"function",function:target.function}:"path"in target?{type:"path",path:target.path,...target.requestMethod!==void 0&&{requestMethod:target.requestMethod}}:{type:"queue",topic:target.topic}}})}import path3 from"path";function toOrchestratorService(sidecar){let{type:_type,...subscriber}=sidecar;return{...subscriber,schema:"experimentalServices",type:"worker",trigger:"queue"}}async function collectBuilderDevSidecars({builds,workPath,services=[]}){let builderSpecs=new Set(builds.map(build=>build.use)),buildersWithPkgs=await importBuilders(builderSpecs,workPath),servicesByBuilder=new Map(services.map(service=>[service.builder,service])),sidecars=(await Promise.all(builds.map(async build=>{let builder=buildersWithPkgs.get(build.use)?.builder;if(!builder)throw dev.DEV_BUILDER_LOAD_FAILED({use:build.use});let service=servicesByBuilder.get(build),serviceRoot=service?.root??".",sidecars2=await builder.getDevSidecars?.({workPath:path3.join(workPath,serviceRoot),build,...service?{service}:{}})??[];return service?sidecars2.map(sidecar=>({...sidecar,name:`${service.name}-${sidecar.name}`,workspace:serviceRoot})):sidecars2}))).flat(),names=new Set;for(let sidecar of sidecars){let{name,type}=sidecar;if(type!=="subscriber")throw dev.DEV_SIDECAR_UNSUPPORTED_TYPE({name,type});if(names.has(name))throw dev.DEV_SIDECAR_DUPLICATE_NAME({name});names.add(name)}return sidecars}function nodeHeadersToFetchHeaders(nodeHeaders){let headers=new globalThis.Headers;for(let[name,value]of Object.entries(nodeHeaders))if(Array.isArray(value))for(let val of value)headers.append(name,val);else typeof value<"u"&&headers.set(name,String(value));return headers}var NEVER_COMBINE_RESPONSE_HEADERS=new Set(["set-cookie","www-authenticate","proxy-authenticate"]),COMMA_JOIN_RESPONSE_HEADERS=new Set(["vary"]);function applyChainResponseHeader(res,name,value){if(NEVER_COMBINE_RESPONSE_HEADERS.has(name)){let existing=res.getHeader(name),values=Array.isArray(existing)?existing.map(String):existing!==void 0?[String(existing)]:[];values.push(value),res.setHeader(name,values);return}if(COMMA_JOIN_RESPONSE_HEADERS.has(name)){let existing=res.getHeader(name);res.setHeader(name,existing!==void 0?`${existing}, ${value}`:value);return}res.setHeader(name,value)}var NONOVERRIDABLE_HEADERS=new Set(["host","connection","content-length","transfer-encoding","keep-alive","transfer-encoding","te","upgrade","trailer"]);function applyOverriddenHeaders(reqHeaders,respHeaders){let headers=new globalThis.Headers(respHeaders),overriddenHeaders=headers.get("x-middleware-override-headers");if(!overriddenHeaders)return headers;let overriddenKeys=new Set;for(let key of overriddenHeaders.split(","))overriddenKeys.add(key.trim());headers.delete("x-middleware-override-headers");for(let key of Object.keys(reqHeaders))!NONOVERRIDABLE_HEADERS.has(key)&&!overriddenKeys.has(key)&&delete reqHeaders[key];for(let key of overriddenKeys.keys()){if(NONOVERRIDABLE_HEADERS.has(key))continue;let valueKey="x-middleware-request-"+key,newValue=headers.get(valueKey);reqHeaders[key]!==newValue&&(newValue?reqHeaders[key]=newValue:delete reqHeaders[key]),headers.delete(valueKey)}return headers}var import_error_utils=__toESM(require_dist(),1);import{parse}from"url";function parseListen(str,defaultPort=3e3){let port=Number(str);if(!isNaN(port))return[port];let url4=parse(str);switch(url4.protocol){case"pipe:":{let cutStr=str.replace(/^pipe:/,"");if(cutStr.slice(0,4)!=="\\\\.\\")throw dev.DEV_INVALID_WINDOWS_PIPE({endpoint:str});return[cutStr]}case"unix:":if(!url4.pathname)throw dev.DEV_INVALID_UNIX_SOCKET({endpoint:str});return[url4.pathname];case"tcp:":return url4.port=url4.port||String(defaultPort),[parseInt(url4.port,10),url4.hostname??void 0];default:if(!url4.slashes){if(url4.protocol===null)return[defaultPort,url4.pathname??void 0];if(port=Number(url4.hostname),url4.protocol&&!isNaN(port))return[port,url4.protocol.substring(0,url4.protocol.length-1)]}throw dev.DEV_INVALID_LISTEN_SCHEME({protocol:url4.protocol})}}function replaceLocalhost(address){return address.replace("[::]","localhost").replace("0.0.0.0","localhost")}import{lstat,readdir,readFile,stat}from"node:fs/promises";import{extname,isAbsolute as isAbsolute2,join as join3,relative as relative3,resolve}from"node:path";import{parse as parseUrl}from"node:url";var MAX_REDIRECTS=1e6,MAX_FILES=100,MAX_URL_LENGTH=2048,VALID_STATUS_CODES=new Set([301,302,303,307,308]),SUPPORTED_EXTENSIONS=new Set([".csv",".json",".jsonl"]),BulkRedirectTable=class{constructor(){this.caseSensitiveByHostPath=new Map;this.caseInsensitiveByHostPath=new Map;this.caseSensitiveByPath=new Map;this.caseInsensitiveByPath=new Map}get size(){return this.caseSensitiveByHostPath.size+this.caseInsensitiveByHostPath.size+this.caseSensitiveByPath.size+this.caseInsensitiveByPath.size}add(redirect2){let{host,pathname}=parseSource(redirect2.source),stored={destination:redirect2.destination,statusCode:redirect2.statusCode,preserveQueryParams:redirect2.preserveQueryParams};if(host){let key=hostPathKey(host,pathname);redirect2.caseSensitive?this.caseSensitiveByHostPath.set(key,stored):this.caseInsensitiveByHostPath.set(key.toLowerCase(),stored);return}redirect2.caseSensitive?this.caseSensitiveByPath.set(pathname,stored):this.caseInsensitiveByPath.set(pathname.toLowerCase(),stored)}lookup(pathname,host){let hostname=host?hostnameFromHostHeader(host):"";if(hostname){let hostKey=hostPathKey(hostname,pathname),hostMatch=this.caseSensitiveByHostPath.get(hostKey)||this.caseInsensitiveByHostPath.get(hostKey.toLowerCase());if(hostMatch)return hostMatch}return this.caseSensitiveByPath.get(pathname)||this.caseInsensitiveByPath.get(pathname.toLowerCase())}};async function getBulkRedirectsSignature(cwd,bulkRedirectsPath){if(!bulkRedirectsPath)return"";let resolved=resolveBulkRedirectsPath(cwd,bulkRedirectsPath);if(!resolved)return`invalid:${bulkRedirectsPath}`;try{let stats=await stat(resolved);if(stats.isFile())return`file:${resolved}:${stats.mtimeMs}:${stats.size}`;if(!stats.isDirectory())return`other:${resolved}:${stats.mtimeMs}`;let files=await listRedirectFiles(resolved),parts=await Promise.all(files.map(async file=>{try{let fileStats=await stat(file);return`${file}:${fileStats.mtimeMs}:${fileStats.size}`}catch{return`${file}:missing`}}));return`dir:${resolved}:${parts.join("|")}`}catch{return`missing:${resolved}`}}async function loadBulkRedirects(cwd,bulkRedirectsPath){let warnings=[],table=new BulkRedirectTable,resolved=resolveBulkRedirectsPath(cwd,bulkRedirectsPath);if(!resolved)return warnings.push(`Skipping bulk redirects path "${bulkRedirectsPath}" because it resolves outside the project directory.`),{table,redirectCount:0,fileCount:0,warnings};let files;try{let stats=await stat(resolved);if(stats.isDirectory())files=await listRedirectFiles(resolved),files.length>MAX_FILES&&(warnings.push(`Bulk redirects directory "${bulkRedirectsPath}" has ${files.length} files; only the first ${MAX_FILES} will be used.`),files=files.slice(0,MAX_FILES));else if(stats.isFile()){let ext=extname(resolved).toLowerCase();if(!SUPPORTED_EXTENSIONS.has(ext))return warnings.push(`Bulk redirects file "${bulkRedirectsPath}" must be a .csv, .json, or .jsonl file.`),{table,redirectCount:0,fileCount:0,warnings};files=[resolved]}else return warnings.push(`Bulk redirects path "${bulkRedirectsPath}" is not a file or directory.`),{table,redirectCount:0,fileCount:0,warnings}}catch(err){if(isNotFound(err))return warnings.push(`Bulk redirects path "${bulkRedirectsPath}" was not found.`),{table,redirectCount:0,fileCount:0,warnings};throw err}let redirectCount=0;for(let file of files){if(redirectCount>=MAX_REDIRECTS){warnings.push(`Bulk redirects limit of ${MAX_REDIRECTS} reached; remaining entries were skipped.`);break}let remaining=MAX_REDIRECTS-redirectCount,parsed=await parseRedirectFile(file,remaining,warnings,cwd);for(let redirect2 of parsed)table.add(redirect2),redirectCount++}let duplicateCount=redirectCount-table.size;return duplicateCount>0&&warnings.push(`Bulk redirects contain ${duplicateCount} duplicate ${duplicateCount===1?"source":"sources"}; the last occurrence wins.`),{table,redirectCount,fileCount:files.length,warnings}}function resolveBulkRedirect(table,reqUrl,host){let parsed=parseUrl(reqUrl),match=table.lookup(parsed.pathname||"/",host);if(!match)return;let location=match.destination;return match.preserveQueryParams&&parsed.search&&(location=appendQueryParams(location,parsed.search)),{location,statusCode:match.statusCode}}function appendQueryParams(destination,search){let query=search.startsWith("?")?search.slice(1):search;return query?destination.includes("?")?`${destination}&${query}`:`${destination}?${query}`:destination}function resolveBulkRedirectsPath(cwd,bulkRedirectsPath){let projectRoot=resolve(cwd),resolved=resolve(projectRoot,bulkRedirectsPath),relativeFromRoot=relative3(projectRoot,resolved);return relativeFromRoot.startsWith("..")||isAbsolute2(relativeFromRoot)?null:resolved}async function listRedirectFiles(dir){let files=[];return await walk(dir,files),files.sort(),files}async function walk(dir,files){let entries=await readdir(dir);for(let entry of entries){let fullPath=join3(dir,entry),stats=await lstat(fullPath);stats.isDirectory()?await walk(fullPath,files):stats.isFile()&&SUPPORTED_EXTENSIONS.has(extname(fullPath).toLowerCase())&&files.push(fullPath)}}async function parseRedirectFile(file,remaining,warnings,cwd){let rel=relative3(cwd,file)||file,ext=extname(file).toLowerCase(),content;try{content=stripBom(await readFile(file,"utf8"))}catch(err){return warnings.push(`Failed to read bulk redirects file "${rel}": ${errorMessage(err)}`),[]}try{return ext===".csv"?parseCsvRedirects(content,remaining,warnings,rel):ext===".jsonl"?parseJsonlRedirects(content,remaining,warnings,rel):parseJsonRedirects(content,remaining,warnings,rel)}catch(err){return warnings.push(`Failed to parse bulk redirects file "${rel}": ${errorMessage(err)}`),[]}}function parseJsonRedirects(content,remaining,warnings,rel){let parsed=JSON.parse(content);return Array.isArray(parsed)?normalizeRedirects(parsed,remaining,warnings,rel):(warnings.push(`Bulk redirects file "${rel}" must contain a JSON array of redirects.`),[])}function parseJsonlRedirects(content,remaining,warnings,rel){let rows=[],lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){let line=lines[i].trim();if(line)try{rows.push(JSON.parse(line))}catch{warnings.push(`Skipping invalid JSONL in "${rel}" at line ${i+1}.`)}}return normalizeRedirects(rows,remaining,warnings,rel)}var CSV_HEADER_ALIASES={source:"source",destination:"destination",permanent:"permanent",statuscode:"statusCode",casesensitive:"caseSensitive",preservequeryparams:"preserveQueryParams"};function parseCsvRedirects(content,remaining,warnings,rel){let lines=content.split(/\r?\n/).filter(line=>line.trim().length>0);if(lines.length===0)return warnings.push(`Bulk redirects CSV "${rel}" is empty.`),[];let headers=parseCsvLine(lines[0]).map(header=>CSV_HEADER_ALIASES[header.trim().toLowerCase()]);if(!headers.includes("source")||!headers.includes("destination"))return warnings.push(`Bulk redirects CSV "${rel}" must have "source" and "destination" columns.`),[];let rows=[];for(let i=1;i<lines.length;i++){let values=parseCsvLine(lines[i]),row={};for(let col=0;col<headers.length;col++){let header=headers[col];header&&(row[header]=values[col]??"")}rows.push(row)}return normalizeRedirects(rows,remaining,warnings,rel)}function normalizeRedirects(rows,remaining,warnings,rel){let redirects=[];for(let i=0;i<rows.length;i++){if(redirects.length>=remaining){warnings.push(`Bulk redirects limit of ${MAX_REDIRECTS} reached while reading "${rel}"; remaining entries were skipped.`);break}let row=rows[i];if(!row||typeof row!="object"){warnings.push(`Skipping invalid redirect in "${rel}" at index ${i}.`);continue}let record=row,source=asTrimmedString(record.source),destination=asTrimmedString(record.destination);if(!source||!destination){warnings.push(`Skipping redirect in "${rel}" at index ${i}: source and destination are required.`);continue}if(source.length>MAX_URL_LENGTH||destination.length>MAX_URL_LENGTH){warnings.push(`Skipping redirect in "${rel}" at index ${i}: source and destination must be at most ${MAX_URL_LENGTH} characters.`);continue}let statusCode;if(record.statusCode!==void 0&&record.statusCode!==""){let parsedStatus=parseStatusCode(record.statusCode);if(parsedStatus===void 0){warnings.push(`Skipping redirect in "${rel}" at index ${i}: statusCode must be one of ${[...VALID_STATUS_CODES].join(", ")}.`);continue}statusCode=parsedStatus}else statusCode=parseBoolean(record.permanent)??!1?308:307;redirects.push({source,destination,statusCode,caseSensitive:parseBoolean(record.caseSensitive)??!1,preserveQueryParams:parseBoolean(record.preserveQueryParams)??!1})}return redirects}function parseSource(source){if(/^https?:\/\//i.test(source))try{let parsed=new URL(source);return{host:parsed.hostname.toLowerCase(),pathname:parsed.pathname||"/"}}catch{return{host:null,pathname:source}}return{host:null,pathname:source||"/"}}function hostPathKey(host,pathname){return`${host}\0${pathname}`}function hostnameFromHostHeader(hostHeader){let trimmed=hostHeader.trim();if(!trimmed)return"";if(trimmed.startsWith("[")){let end=trimmed.indexOf("]");return end===-1?trimmed.toLowerCase():trimmed.slice(1,end).toLowerCase()}let colon=trimmed.lastIndexOf(":");return colon!==-1&&trimmed.indexOf(":")===colon?trimmed.slice(0,colon).toLowerCase():trimmed.toLowerCase()}function parseBoolean(value){if(typeof value=="boolean")return value;if(typeof value=="number")return value===1?!0:value===0?!1:void 0;if(typeof value!="string")return;let normalized=value.trim().toLowerCase();if(normalized==="t"||normalized==="true")return!0;if(normalized==="f"||normalized==="false")return!1}function parseStatusCode(value){let n=typeof value=="number"?value:typeof value=="string"?Number(value.trim()):NaN;return VALID_STATUS_CODES.has(n)?n:void 0}function asTrimmedString(value){if(typeof value!="string")return;let trimmed=value.trim();return trimmed||void 0}function parseCsvLine(line){let fields=[],current="",inQuotes=!1;for(let i=0;i<line.length;i++){let char=line[i];inQuotes?char==='"'?line[i+1]==='"'?(current+='"',i++):inQuotes=!1:current+=char:char==='"'?inQuotes=!0:char===","?(fields.push(current),current=""):current+=char}return fields.push(current),fields}function stripBom(content){return content.charCodeAt(0)===65279?content.slice(1):content}function isNotFound(err){return typeof err=="object"&&err!==null&&"code"in err&&err.code==="ENOENT"}function errorMessage(err){return err instanceof Error?err.message:String(err)}var DEV_SERVER_PORT_BIND_TIMEOUT=(0,import_ms6.default)("5m"),DEV_QUEUES_DEFAULT_VISIBILITY_TIMEOUT_SECONDS=60,DEV_RUNTIME_CACHE_MAX_ITEM_SIZE=2*1024*1024,DEV_RUNTIME_CACHE_ONE_YEAR_SECONDS=31536e3,frameworkRuntimeSet=new Set(import_frameworks3.frameworkList.map(f=>f.useRuntime?.use||"@vercel/static-build"));function isApiDirBuild(build){let src=build.src?.replace(/^\.\//,"");return typeof src=="string"&&src.startsWith("api/")}function sortBuilders(buildA,buildB){return buildA&&buildA.use&&(0,import_fs_detectors2.isOfficialRuntime)("static-build",buildA.use)?1:buildB&&buildB.use&&(0,import_fs_detectors2.isOfficialRuntime)("static-build",buildB.use)?-1:0}var DevServer=class{constructor(cwd,options){this.initialDevCommandStarted=!1;this.devCommandStarts=new Set;this.functionDispatchReady=!1;this.functionReconciliations=0;this.configGeneration=0;this.unmatchedQueuePatterns=new Set;this.functionRegistry={functions:new Map,schedules:[],unmatchedPatterns:[]};this.responseTransformsByReq=new WeakMap;this.shouldBuildInDev=build=>{if(build.config?.scheduleFunction||!this.shouldUseServicesOrchestrator()&&isApiDirBuild(build))return!0;let{name}=(0,import_npm_package_arg.default)(build.use);return!frameworkRuntimeSet.has(name||"")};this.clearVercelConfigPromise=()=>{this.getVercelConfigPromise=null};this.getExtensionlessFile=path6=>{let ext=extname2(path6);return this.apiDir&&path6.startsWith(this.apiDir+"/")&&this.apiExtensions.has(ext)?path6.slice(0,-ext.length):null};this.devServerHandler=async(req,res)=>{if(await this.handleSchedulesProxyRequest(req,res))return;await this.startPromise;let requestId=generateRequestId(this.podId);if(this.stopping){res.setHeader("Connection","close"),await this.send404(req,res,requestId);return}let method=req.method||"GET";output_manager_default.debug(`${import_chalk2.default.bold(method)} ${req.url}`);try{let vercelConfig=await this.getVercelConfig();await this.serveProjectAsNowV2(req,res,requestId,vercelConfig)}catch(err){console.error(err),(0,import_error_utils.isError)(err)&&typeof err.stack=="string"&&output_manager_default.debug(err.stack),res.finished||(res.statusCode=500,res.end((0,import_error_utils.errorToString)(err)))}};this.handleSchedulesRoute=async(req,res,pathname)=>{if(this.stopping){res.writeHead(503),res.end("Local Schedules is stopping");return}await handleSchedulesRequest(this.scheduleBroker,this.projectId??"prj_local",req,res,pathname)};this.exitWithStatus=async(match,routeResult,phase,req,res,requestId,responseTransforms)=>{let{status,headers,dest}=routeResult,location=headers.location||dest;if(status&&location&&300<=status&&status<=399)return output_manager_default.debug(`Route found with redirect status code ${status}`),await this.sendRedirect(req,res,requestId,location,status,responseTransforms),!0;if(!match&&status&&phase!=="miss"){if(routeResult.userDest)return!1;output_manager_default.debug(`Route found with with status code ${status}`);let errorHeaders={...headers};return responseTransforms&&applyResponseTransforms(errorHeaders,responseTransforms),await this.sendError(req,res,requestId,"",status,errorHeaders),!0}return!1};this.handleQueuesRoute=async(req,res,pathname)=>{if(!this.queueBroker){res.writeHead(503),res.end("Queues broker not initialized");return}if(!pathname.startsWith(DEV_QUEUE_API_PREFIX)){res.writeHead(404),res.end("Not Found");return}let topicPath=pathname.slice(DEV_QUEUE_API_PREFIX.length),sendMatch=topicPath.match(/^([A-Za-z0-9_-]+)$/);if(req.method==="POST"&&sendMatch){let topic=sendMatch[1],contentType2=req.headers["content-type"]||"application/json",payload=await(0,import_raw_body2.default)(req),retentionHeader=req.headers["vqs-retention-seconds"],retentionSeconds=retentionHeader&&!isNaN(parseInt(retentionHeader,10))?parseInt(retentionHeader,10):void 0,delayHeader=req.headers["vqs-delay-seconds"],delaySeconds=delayHeader&&!isNaN(parseInt(delayHeader,10))?parseInt(delayHeader,10):void 0,idempotencyKey=req.headers["vqs-idempotency-key"],{messageId}=this.queueBroker.enqueue(topic,payload,contentType2,{retentionSeconds,delaySeconds,idempotencyKey});res.writeHead(201,{"Content-Type":"application/json","Vqs-Message-Id":messageId}),res.end(JSON.stringify({messageId}));return}let receiveByIdMatch=topicPath.match(/^([A-Za-z0-9_-]+)\/consumer\/([A-Za-z0-9_-]+)\/id\/([^/]+)$/);if(req.method==="POST"&&receiveByIdMatch){let[,queueName,consumer,messageId]=receiveByIdMatch,originalMessageId=this.queueBroker.getOriginalMessageIdForDuplicate(queueName,messageId);if(originalMessageId){res.writeHead(409,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"This messageId was a duplicate - use originalMessageId instead",originalMessageId}));return}let result=this.queueBroker.receiveById(queueName,messageId,consumer);if(!result){res.writeHead(404),res.end("Message not found");return}let boundary=`----vcdevboundary${randomBytes2(8).toString("hex")}`,partHeaders=[`Vqs-Message-Id: ${messageId}`,`Vqs-Delivery-Count: ${result.deliveryCount}`,`Vqs-Timestamp: ${result.createdAt}`,`Vqs-Receipt-Handle: ${result.receiptHandle}`,`Content-Type: ${result.contentType}`].join(`\r
41
+ `);let installCommand=typeof config?.installCommand=="string"?config.installCommand.trim():"";installCommand?await this.runInstallCommand(installCommand,workspacePath,logger):await this.maybeInstallJSDependencies(workspacePath,logger)}async runBuffered(logger,task){let captured=[],bufStdout=new Writable({write(chunk,_enc,cb){let b=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);captured.push(["stdout",b]),output_manager_default.debugEnabled&&logger.stdout.write(b),cb()}}),bufStderr=new Writable({write(chunk,_enc,cb){let b=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);captured.push(["stderr",b]),output_manager_default.debugEnabled&&logger.stderr.write(b),cb()}});try{await task(bufStdout,bufStderr)}catch(err){for(let[channel,chunk]of captured)logger[channel].write(chunk);throw err}}async runInstallCommand(command,workspacePath,logger){await this.runBuffered(logger,(stdout,stderr)=>new Promise((resolve3,reject)=>{output_manager_default.debug(`Running install command: "${command}" in ${workspacePath}`);let child=(0,import_build_utils5.spawnCommand)(command,{cwd:workspacePath,stdio:["inherit","pipe","pipe"]});child.stdout?.on("data",chunk=>stdout.write(chunk)),child.stderr?.on("data",chunk=>stderr.write(chunk)),child.on("error",reject),child.on("exit",(code,signal)=>{code===0?resolve3():reject(new import_build_utils5.NowBuildError({code:"INSTALL_COMMAND_FAILED",message:`Install command "${command}" failed with code ${code}, signal ${signal}`}))})}))}async maybeInstallJSDependencies(workspacePath,logger){await this.runBuffered(logger,async(stdout,stderr)=>{try{await(0,import_build_utils5.runNpmInstall)(workspacePath,[],void 0,this.installMeta,void 0,{stdout,stderr})}catch(err){throw new import_build_utils5.NowBuildError({code:"NODE_DEPENDENCY_SYNC_FAILED",message:`Failed to install Node.JS dependencies: ${err instanceof Error?err.message:String(err)}`})}})}startCronSchedulers(){for(let[name,managed]of this.managedServices){let service=this.services.find(candidate=>candidate.name===name),crons=managed.crons&&managed.crons.length>0?managed.crons:service&&(0,import_build_utils5.isExperimentalService)(service)&&(0,import_build_utils5.isScheduleTriggeredService)(service)&&service.schedule?(0,import_service_schedules.getStaticServiceSchedules)(service.schedule).map(schedule=>({path:(0,import_build_utils5.getInternalServiceCronPath)(name,service.entrypoint||service.builder.src||"index",service.handlerFunction||"cron"),schedule})):[];if(crons.length!==0)for(let cron of crons)output_manager_default.debug(`Scheduling job service ${import_chalk.default.bold(name)} (${import_chalk.default.cyan(cron.schedule)})`),this.scheduleCronTrigger(name,cron.path,cron.schedule,managed)}}scheduleCronTrigger(serviceName,cronPath,schedule,managed){let delayMs=getNextCronDelay(schedule);if(delayMs===null){output_manager_default.warn(`Could not parse cron schedule "${schedule}" for service "${serviceName}", skipping auto-trigger`);return}let timer=setTimeout(async()=>{if(!this.stopping){output_manager_default.debug(`Triggering scheduled job ${import_chalk.default.bold(serviceName)} (schedule: ${import_chalk.default.cyan(schedule)})`);try{let url4=`http://${managed.host}:${managed.port}${cronPath}`,res=await fetch(url4,{method:"POST"});output_manager_default.debug(`Cron trigger for "${serviceName}" responded with status ${res.status}`)}catch(err){output_manager_default.error(`Cron trigger for "${serviceName}" failed: ${err instanceof Error?err.message:String(err)}`)}this.scheduleCronTrigger(serviceName,cronPath,schedule,managed)}},delayMs);this.cronTimers.push(timer)}};var import_ms5=__toESM(require_ms(),1);import{randomBytes}from"crypto";var import_build_utils6=__toESM(require_build_utils(),1);var DEFAULT_RETRY_AFTER=(0,import_ms5.default)("1m"),DEFAULT_MAX_DELIVERIES=32,DEFAULT_INITIAL_DELAY=0,DEFAULT_VISIBILITY_TIMEOUT=(0,import_ms5.default)("1m"),DEFAULT_RETENTION=(0,import_ms5.default)("1h"),TICK_INTERVAL2=(0,import_ms5.default)("1s");function topicPatternToRegex(pattern){let parts=pattern.split("*").map(s=>s.replace(/-/g,"\\-"));return new RegExp(`^${parts.join("[A-Za-z0-9_\\-]*")}$`)}var QueueBroker=class{constructor(services,getServiceOrigin){this.getServiceOrigin=getServiceOrigin;this.messages=new Map;this.idempotencyRecords=new Map;this.duplicateMessages=new Map;this.consumerGroups=[];this.deliveryState=new Map;this.registerServices(services),this.tickTimer=setInterval(()=>this.tick(),TICK_INTERVAL2),this.tickTimer.unref()}registerServices(services){let ids=new Set;for(let service of services.filter(import_build_utils6.isQueueBackedService))for(let{topic}of(0,import_build_utils6.getServiceQueueTopicConfigs)(service)){let consumerGroup=service.consumer??service.name,id=`${consumerGroup}::${topic}`,existing=this.consumerGroups.find(group=>group.id===id);if(ids.has(id)||existing?.serviceOriginFn||existing?.resolveFunction)throw dev.DEV_QUEUE_CONSUMER_DUPLICATE({consumerGroup,topic});ids.add(id)}for(let service of services){if(!(0,import_build_utils6.isQueueBackedService)(service))continue;let topicConfigs=(0,import_build_utils6.getServiceQueueTopicConfigs)(service),consumerGroup=service.consumer??service.name;for(let topicConfig of topicConfigs){let topicPattern=topicConfig.topic,id=`${consumerGroup}::${topicPattern}`,existingGroup=this.consumerGroups.find(group2=>group2.id===id);if(existingGroup&&!existingGroup.serviceOriginFn&&!existingGroup.resolveFunction){existingGroup.serviceName=service.name,existingGroup.serviceOriginFn=()=>this.getServiceOrigin(service.name),existingGroup.retryAfterMs=topicConfig.retryAfterSeconds!==void 0?topicConfig.retryAfterSeconds*1e3:DEFAULT_RETRY_AFTER,existingGroup.initialDelayMs=topicConfig.initialDelaySeconds!==void 0?topicConfig.initialDelaySeconds*1e3:DEFAULT_INITIAL_DELAY,this.activatePushGroup(existingGroup);continue}if(existingGroup)throw dev.DEV_QUEUE_CONSUMER_DUPLICATE({consumerGroup,topic:topicPattern});let group={id,name:consumerGroup,serviceName:service.name,topicPattern,topicRegex:topicPatternToRegex(topicPattern),serviceOriginFn:()=>this.getServiceOrigin(service.name),retryAfterMs:topicConfig.retryAfterSeconds!==void 0?topicConfig.retryAfterSeconds*1e3:DEFAULT_RETRY_AFTER,maxDeliveries:DEFAULT_MAX_DELIVERIES,initialDelayMs:topicConfig.initialDelaySeconds!==void 0?topicConfig.initialDelaySeconds*1e3:DEFAULT_INITIAL_DELAY};this.consumerGroups.push(group),this.deliveryState.set(group.id,this.createRetainedDeliveries(group)),this.activatePushGroup(group)}}}updateServiceSubscriptions(serviceName,subscriptions){if(subscriptions.length===0)return;let kept=[];for(let group of this.consumerGroups)group.serviceName===serviceName?this.deliveryState.delete(group.id):kept.push(group);this.consumerGroups=kept;for(let subscription of subscriptions){let id=`${subscription.consumer}::${subscription.topic}`,existingGroup=this.consumerGroups.find(group2=>group2.id===id);if(existingGroup&&!existingGroup.serviceOriginFn&&!existingGroup.resolveFunction){existingGroup.serviceName=serviceName,existingGroup.serviceOriginFn=()=>this.getServiceOrigin(serviceName),existingGroup.retryAfterMs=subscription.retryAfterSeconds!==void 0?subscription.retryAfterSeconds*1e3:DEFAULT_RETRY_AFTER,existingGroup.maxDeliveries=subscription.maxDeliveries??DEFAULT_MAX_DELIVERIES,existingGroup.initialDelayMs=subscription.initialDelaySeconds!==void 0?subscription.initialDelaySeconds*1e3:DEFAULT_INITIAL_DELAY,this.activatePushGroup(existingGroup);continue}if(existingGroup){output_manager_default.debug(`Queue consumer "${subscription.consumer}" is already registered for topic "${subscription.topic}"; keeping the first registration`);continue}let group={id,name:subscription.consumer,serviceName,topicPattern:subscription.topic,topicRegex:topicPatternToRegex(subscription.topic),serviceOriginFn:()=>this.getServiceOrigin(serviceName),retryAfterMs:subscription.retryAfterSeconds!==void 0?subscription.retryAfterSeconds*1e3:DEFAULT_RETRY_AFTER,maxDeliveries:subscription.maxDeliveries??DEFAULT_MAX_DELIVERIES,initialDelayMs:subscription.initialDelaySeconds!==void 0?subscription.initialDelaySeconds*1e3:DEFAULT_INITIAL_DELAY};this.consumerGroups.push(group),this.deliveryState.set(group.id,this.createRetainedDeliveries(group)),this.activatePushGroup(group)}output_manager_default.debug(`Queue consumer groups for service "${serviceName}" updated from ${subscriptions.length} introspected subscription(s)`)}validateFunctionSubscriptions(subscriptions){let ids=new Set;for(let subscription of subscriptions){let id=`${subscription.consumer}::${subscription.topic}`,existing=this.consumerGroups.find(group=>group.id===id);if(ids.has(id)||existing?.serviceOriginFn&&!existing.configOwned)throw dev.DEV_QUEUE_CONSUMER_DUPLICATE({consumerGroup:subscription.consumer,topic:subscription.topic});ids.add(id)}}setFunctionSubscriptions(subscriptions,resolve3){this.validateFunctionSubscriptions(subscriptions);let ids=new Set(subscriptions.map(subscription=>`${subscription.consumer}::${subscription.topic}`));for(let group of this.consumerGroups)group.configOwned&&!ids.has(group.id)&&(delete group.configOwned,delete group.resolveFunction);for(let subscription of subscriptions){let id=`${subscription.consumer}::${subscription.topic}`,group=this.consumerGroups.find(group2=>group2.id===id);group||(group={id,name:subscription.consumer,topicPattern:subscription.topic,topicRegex:topicPatternToRegex(subscription.topic),retryAfterMs:DEFAULT_RETRY_AFTER,maxDeliveries:DEFAULT_MAX_DELIVERIES,initialDelayMs:DEFAULT_INITIAL_DELAY},this.consumerGroups.push(group),this.deliveryState.set(id,this.createRetainedDeliveries(group))),group.configOwned=!0,group.resolveFunction=()=>resolve3(subscription.outputPath),group.retryAfterMs=subscription.retryAfterSeconds===void 0?DEFAULT_RETRY_AFTER:subscription.retryAfterSeconds*1e3,group.maxDeliveries=subscription.maxDeliveries??DEFAULT_MAX_DELIVERIES,group.initialDelayMs=(subscription.initialDelaySeconds??0)*1e3,this.activatePushGroup(group)}}enqueue(queueName,payload,contentType2,options){let now=Date.now(),messageId=randomBytes(16).toString("hex"),retentionMs=(options?.retentionSeconds??0)>0?options.retentionSeconds*1e3:DEFAULT_RETENTION,idempotencyRecordKey=options?.idempotencyKey?`${queueName}:${options.idempotencyKey}`:void 0;if(idempotencyRecordKey){let record=this.idempotencyRecords.get(idempotencyRecordKey);if(record&&record.expiresAt>Date.now())return this.duplicateMessages.set(messageId,{queueName,originalMessageId:record.messageId,expiresAt:Date.now()+retentionMs}),output_manager_default.debug(`queues: skipped duplicate message for queue "${queueName}"`),{messageId};record&&this.idempotencyRecords.delete(idempotencyRecordKey)}idempotencyRecordKey&&this.idempotencyRecords.set(idempotencyRecordKey,{messageId,expiresAt:Date.now()+retentionMs});let message2={messageId,payload,contentType:contentType2,queueName,createdAt:new Date(now).toISOString(),retentionMs,visibleAt:(options?.delaySeconds??0)>0?now+options.delaySeconds*1e3:0};this.messages.set(messageId,message2),output_manager_default.debug(`queues: stored message ${messageId} for queue "${queueName}"`);let matchingGroups=this.consumerGroups.filter(g=>g.topicRegex.test(queueName));matchingGroups.length===0&&output_manager_default.debug(`queues: no consumer group matches topic "${queueName}", message stored but not dispatched`);for(let group of matchingGroups){let groupDeliveries=this.deliveryState.get(group.id),initialVisibleAt=group.initialDelayMs>0?now+group.initialDelayMs:0,visibleAt=Math.max(message2.visibleAt,initialVisibleAt);groupDeliveries.set(messageId,{status:"pending",deliveryCount:0,receiptHandle:"",visibleAt,leaseExpiresAt:0}),visibleAt<=now&&(group.serviceOriginFn||group.resolveFunction)&&this.dispatchToConsumer(message2,group).catch(err=>{output_manager_default.debug(`queues: unexpected dispatch error: ${err}`)})}return{messageId}}getOriginalMessageIdForDuplicate(queueName,messageId){let duplicate=this.duplicateMessages.get(messageId);return!duplicate||duplicate.queueName!==queueName?null:duplicate.expiresAt<=Date.now()?(this.duplicateMessages.delete(messageId),null):duplicate.originalMessageId}receiveById(queueName,messageId,consumerGroup){let message2=this.messages.get(messageId);if(!message2||message2.queueName!==queueName||this.isMessageExpired(message2))return null;let group=this.getOrCreatePullGroup(queueName,consumerGroup),state=this.deliveryState.get(group.id)?.get(messageId);if(!state)return null;if(state.status==="pending"){if(state.visibleAt>Date.now())return null;state.status="in-flight",state.receiptHandle=randomBytes(16).toString("hex"),state.deliveryCount++,state.leaseExpiresAt=Date.now()+DEFAULT_VISIBILITY_TIMEOUT}return{messageId:message2.messageId,payload:message2.payload,contentType:message2.contentType,deliveryCount:state.deliveryCount,createdAt:message2.createdAt,receiptHandle:state.receiptHandle}}receiveMessages(queueName,consumerGroup,options){let group=this.getOrCreatePullGroup(queueName,consumerGroup),groupDeliveries=this.deliveryState.get(group.id);if(!groupDeliveries)return[];let now=Date.now(),limit=Math.min(Math.max(options?.limit??1,1),10),visibilityTimeoutMs=(options?.visibilityTimeoutSeconds??DEFAULT_VISIBILITY_TIMEOUT/1e3)*1e3,results=[];for(let[messageId,state]of groupDeliveries){let message2=this.messages.get(messageId);if(!message2){groupDeliveries.delete(messageId);continue}if(this.isMessageExpired(message2,now)){this.deleteMessage(messageId);continue}if(message2.queueName!==queueName||state.status!=="pending"||state.visibleAt>now)continue;let receiptHandle=randomBytes(16).toString("hex");if(state.status="in-flight",state.receiptHandle=receiptHandle,state.deliveryCount++,state.leaseExpiresAt=Date.now()+visibilityTimeoutMs,results.push({messageId:message2.messageId,payload:message2.payload,contentType:message2.contentType,deliveryCount:state.deliveryCount,createdAt:message2.createdAt,receiptHandle}),results.length>=limit)break}return results}acknowledge(messageId,consumerGroup,receiptHandle){let{deliveries:groupDeliveries,state}=this.findDeliveryState(messageId,consumerGroup);return!groupDeliveries||!state?!1:state.receiptHandle&&state.receiptHandle!==receiptHandle?(output_manager_default.debug(`queues: ACK rejected for ${messageId} in group "${consumerGroup}" - receipt handle mismatch`),!1):(state.status="acked",groupDeliveries.delete(messageId),output_manager_default.debug(`queues: ACK message ${messageId} in group "${consumerGroup}"`),!0)}changeVisibility(messageId,consumerGroup,receiptHandle,timeoutSeconds){let{state}=this.findDeliveryState(messageId,consumerGroup);return!state||state.status!=="in-flight"||state.receiptHandle&&state.receiptHandle!==receiptHandle?!1:(state.leaseExpiresAt=Date.now()+timeoutSeconds*1e3,output_manager_default.debug(`queues: visibility for ${messageId} in group "${consumerGroup}" extended by ${timeoutSeconds}s`),!0)}findMessageIdByReceiptHandle(consumerGroup,receiptHandle){for(let group of this.consumerGroups){if(group.name!==consumerGroup)continue;let deliveries=this.deliveryState.get(group.id);if(deliveries){for(let[messageId,state]of deliveries)if(state.receiptHandle===receiptHandle)return messageId}}return null}findDeliveryState(messageId,serviceName){for(let group of this.consumerGroups){if(group.name!==serviceName)continue;let deliveries=this.deliveryState.get(group.id);if(!deliveries)continue;let state=deliveries.get(messageId);if(state)return{deliveries,state}}return{deliveries:null,state:null}}getOrCreatePullGroup(queueName,consumerGroup){let existingGroup=this.consumerGroups.find(group2=>group2.name===consumerGroup&&group2.topicRegex.test(queueName));if(existingGroup)return existingGroup;let group={id:`${consumerGroup}::${queueName}`,name:consumerGroup,topicPattern:queueName,topicRegex:topicPatternToRegex(queueName),retryAfterMs:DEFAULT_RETRY_AFTER,maxDeliveries:DEFAULT_MAX_DELIVERIES,initialDelayMs:DEFAULT_INITIAL_DELAY},deliveries=new Map;for(let message2 of this.messages.values())message2.queueName!==queueName||this.isMessageExpired(message2)||deliveries.set(message2.messageId,{status:"pending",deliveryCount:0,receiptHandle:"",visibleAt:message2.visibleAt,leaseExpiresAt:0});return this.consumerGroups.push(group),this.deliveryState.set(group.id,deliveries),group}isMessageExpired(message2,now=Date.now()){return new Date(message2.createdAt).getTime()+message2.retentionMs<now}deleteMessage(messageId){this.messages.delete(messageId);for(let groupDeliveries of this.deliveryState.values())groupDeliveries.delete(messageId)}createRetainedDeliveries(group){let deliveries=new Map;for(let message2 of this.messages.values())!group.topicRegex.test(message2.queueName)||this.isMessageExpired(message2)||deliveries.set(message2.messageId,{status:"pending",deliveryCount:0,receiptHandle:"",visibleAt:Math.max(message2.visibleAt,new Date(message2.createdAt).getTime()+group.initialDelayMs),leaseExpiresAt:0});return deliveries}activatePushGroup(group){if(!group.serviceOriginFn&&!group.resolveFunction)return;let now=Date.now(),deliveries=this.deliveryState.get(group.id);if(deliveries)for(let[messageId,state]of deliveries){let message2=this.messages.get(messageId);!message2||state.status!=="pending"||(state.visibleAt=Math.max(state.visibleAt,new Date(message2.createdAt).getTime()+group.initialDelayMs),state.visibleAt<=now&&this.dispatchToConsumer(message2,group).catch(err=>{output_manager_default.debug(`queues: unexpected dispatch error: ${err}`)}))}}async dispatchToConsumer(message2,group){let groupDeliveries=this.deliveryState.get(group.id);if(!groupDeliveries)return;let state=groupDeliveries.get(message2.messageId);if(!state||state.status!=="pending")return;if(state.deliveryCount>=group.maxDeliveries){output_manager_default.debug(`queues: message ${message2.messageId} exceeded maxDeliveries (${group.maxDeliveries}) for group "${group.name}", dropping`),groupDeliveries.delete(message2.messageId);return}let upstream=group.serviceOriginFn?.(),dispatch=group.resolveFunction?.();if(!upstream&&!dispatch){state.visibleAt=Date.now()+TICK_INTERVAL2;return}let receiptHandle=randomBytes(16).toString("hex");state.status="in-flight",state.receiptHandle=receiptHandle,state.deliveryCount++,state.leaseExpiresAt=Date.now()+DEFAULT_VISIBILITY_TIMEOUT;let now=new Date().toISOString(),expiresAt=new Date(new Date(message2.createdAt).getTime()+message2.retentionMs).toISOString();output_manager_default.debug(`queues: dispatching v2beta callback to worker "${group.name}"`);try{let request={method:"POST",headers:{"content-type":message2.contentType,"ce-type":"com.vercel.queue.v2beta","ce-specversion":"1.0","ce-source":`/topic/${message2.queueName}/consumer/${group.name}`,"ce-id":message2.messageId,"ce-time":now,"ce-vqsmessageid":message2.messageId,"ce-vqsqueuename":message2.queueName,"ce-vqsconsumergroup":group.name,"ce-vqsreceipthandle":receiptHandle,"ce-vqsdeliverycount":String(state.deliveryCount),"ce-vqscreatedat":message2.createdAt,"ce-vqsexpiresat":expiresAt,"ce-vqsregion":"dev1"},body:message2.payload},response=dispatch?await dispatch(request):await directFetch(`${upstream}/`,request);if(response===null){state.receiptHandle===receiptHandle&&state.status==="in-flight"&&(state.status="pending",state.deliveryCount--,state.receiptHandle="",state.leaseExpiresAt=0,state.visibleAt=Date.now()+TICK_INTERVAL2);return}response.ok||(output_manager_default.debug(`queues: worker "${group.name}" returned ${response.status} for message ${message2.messageId}`),this.handleDeliveryFailure(message2.messageId,group,receiptHandle))}catch(err){output_manager_default.debug(`queues: failed to dispatch CloudEvent to "${group.name}": ${err}`),this.handleDeliveryFailure(message2.messageId,group,receiptHandle)}}handleDeliveryFailure(messageId,group,receiptHandle){let groupDeliveries=this.deliveryState.get(group.id);if(!groupDeliveries)return;let state=groupDeliveries.get(messageId);!state||state.receiptHandle!==receiptHandle||(state.status="pending",state.visibleAt=Date.now()+group.retryAfterMs,state.leaseExpiresAt=0)}tick(){let now=Date.now();for(let[key,record]of this.idempotencyRecords)record.expiresAt<=now&&this.idempotencyRecords.delete(key);for(let[messageId,record]of this.duplicateMessages)record.expiresAt<=now&&this.duplicateMessages.delete(messageId);for(let[messageId,message2]of this.messages)this.isMessageExpired(message2,now)&&this.deleteMessage(messageId);for(let group of this.consumerGroups){let groupDeliveries=this.deliveryState.get(group.id);if(groupDeliveries)for(let[messageId,state]of groupDeliveries){let message2=this.messages.get(messageId);if(!message2){groupDeliveries.delete(messageId);continue}if(state.status==="in-flight"&&state.leaseExpiresAt<=now){state.deliveryCount>=group.maxDeliveries?(output_manager_default.debug(`queues: message ${messageId} exceeded maxDeliveries (${group.maxDeliveries}) for group "${group.name}", dropping`),groupDeliveries.delete(messageId)):(state.status="pending",state.visibleAt=group.serviceOriginFn||group.resolveFunction?now+group.retryAfterMs:now,state.leaseExpiresAt=0);continue}state.status==="pending"&&state.visibleAt<=now&&(group.serviceOriginFn||group.resolveFunction)&&this.dispatchToConsumer(message2,group).catch(err=>{output_manager_default.debug(`queues: unexpected dispatch error: ${err}`)})}}}stop(){clearInterval(this.tickTimer)}};var import_build_utils7=__toESM(require_build_utils(),1),import_minimatch2=__toESM(require_minimatch(),1);import{posix}from"path";function validPath(value,http2=!1){if(typeof value!="string"||!value)return!1;try{let pathname=http2?value:`/${value}`,decoded=decodeURIComponent(pathname);return pathname.startsWith("/")&&!pathname.startsWith("//")&&!/[\\?#\s]/.test(pathname)&&new URL(pathname,"http://localhost").pathname===pathname&&!/[\\?#\x00-\x1f\x7f]/.test(decoded)&&!/%2f/i.test(pathname)&&!decoded.split("/").some(segment=>segment==="."||segment==="..")&&(http2||!value.endsWith("/")&&!value.includes("//"))}catch{return!1}}async function collectDevFunctions({scopes,workPath,files,config,env}){let builders=await importBuilders(new Set(scopes.map(({build})=>build.use)),workPath),unmatched=new Set(Object.entries(config.functions??{}).filter(([,fn2])=>fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta")).map(([pattern])=>pattern)),functions=new Map,schedules=[];for(let scope of scopes){let{build,target}=scope,builder=builders.get(build.use)?.builder;if(!builder)throw dev.DEV_BUILDER_LOAD_FAILED({use:build.use});let scopedConfig=structuredClone({...config,...build.config,functions:build.config?.functions??(build.config?.zeroConfig?{}:config.functions)}),manifest,{scheduleFunction}=build.config??{};if(scheduleFunction&&build.src)manifest={functions:[{outputPath:scheduleFunction.outputPath,sourceFile:build.src,invocation:{type:"entrypoint",entrypoint:build.src},experimentalTriggers:[{type:"schedule/v1beta"}]}],matchedFunctionPatterns:[]};else if(builder.getDevManifest)manifest=await builder.getDevManifest({workPath,build,files,config:scopedConfig,env});else{manifest={functions:[],matchedFunctionPatterns:[]};let mode=build.config??{};if(target!=="builder"||mode.framework||mode.middleware||mode.buildType==="middleware"||mode.buildType==="app"||mode.serviceName||mode.serviceType||mode.buildpack||!build.src||build.src.includes("<"))continue;let pattern=build.src.replace(/^\//,"");for(let sourceFile of files){if(!(sourceFile===pattern||(0,import_minimatch2.default)(sourceFile,pattern,{dot:!0}))||builder.version!==3&&!(builder.version===-1&&mode.zeroConfig&&pattern.startsWith("api/")&&sourceFile.startsWith("api/"))||/(^|\/)package\.json$/.test(sourceFile)||/^(?:src\/)?middleware\.[^/]+$/.test(sourceFile))continue;let extension=posix.extname(sourceFile),outputPath=mode.zeroConfig&&extension?sourceFile.slice(0,-extension.length):sourceFile,{experimentalTriggers}=await(0,import_build_utils7.getLambdaOptionsFromFunction)({sourceFile,config:scopedConfig});manifest.functions.push({outputPath,sourceFile,invocation:{type:"entrypoint",entrypoint:sourceFile},experimentalTriggers});let matched=Object.keys(scopedConfig.functions??{}).find(key=>sourceFile===key||(0,import_minimatch2.default)(sourceFile,key));matched&&manifest.matchedFunctionPatterns.push(matched)}}if(!Array.isArray(manifest?.functions)||!Array.isArray(manifest?.matchedFunctionPatterns)||manifest.matchedFunctionPatterns.some(pattern=>typeof pattern!="string"))throw dev.DEV_FUNCTION_MANIFEST_INVALID({use:build.use});let scheduleError=validateConfig({schedules:manifest.schedules});if(scheduleError)throw scheduleError;for(let fn2 of manifest.functions){if(!validPath(fn2?.outputPath)||fn2.outputPath.endsWith(".func")||fn2.sourceFile!==void 0&&!validPath(fn2.sourceFile)||!fn2.invocation||(fn2.invocation.type==="http"?!validPath(fn2.invocation.pathname,!0):fn2.invocation.type!=="entrypoint"||!validPath(fn2.invocation.entrypoint))||fn2.experimentalTriggers!==void 0&&!Array.isArray(fn2.experimentalTriggers))throw dev.DEV_FUNCTION_MANIFEST_INVALID({use:build.use});if(functions.has(fn2.outputPath))throw dev.DEV_FUNCTION_OUTPUT_DUPLICATE({outputPath:fn2.outputPath});functions.set(fn2.outputPath,{outputPath:fn2.outputPath,sourceFile:fn2.sourceFile,invocation:structuredClone(fn2.invocation),experimentalTriggers:structuredClone(fn2.experimentalTriggers),scope})}schedules.push(...structuredClone(manifest.schedules??[]));for(let pattern of manifest.matchedFunctionPatterns)unmatched.delete(pattern)}return{functions,schedules,unmatchedPatterns:[...unmatched]}}function deriveQueueSubscriptions(registry){let subscriptions=[],ids=new Set;for(let fn2 of registry.functions.values())for(let trigger of fn2.experimentalTriggers??[]){if(!trigger||typeof trigger.type!="string")throw dev.DEV_FUNCTION_MANIFEST_INVALID({use:fn2.scope.build.use});if(trigger.type!=="queue/v2beta")continue;let{consumer,topic,retryAfterSeconds,initialDelaySeconds,maxDeliveries}=trigger;if(typeof consumer!="string"||!consumer||typeof topic!="string"||!topic||[retryAfterSeconds,initialDelaySeconds,maxDeliveries].some(value=>value!==void 0&&(!Number.isFinite(value)||value<0))||retryAfterSeconds!==void 0&&retryAfterSeconds<=0||maxDeliveries!==void 0&&(!Number.isInteger(maxDeliveries)||maxDeliveries<1))throw dev.DEV_FUNCTION_MANIFEST_INVALID({use:fn2.scope.build.use});let id=`${consumer}::${topic}`;if(ids.has(id))throw dev.DEV_QUEUE_CONSUMER_DUPLICATE({consumerGroup:consumer,topic});ids.add(id),subscriptions.push({outputPath:fn2.outputPath,consumer,topic,retryAfterSeconds,initialDelaySeconds,maxDeliveries})}return subscriptions}var import_raw_body=__toESM(require_raw_body(),1),import_local_schedules=__toESM(require_dist9(),1);import{z}from"zod";var identifier=z.string().min(1).max(256).regex(/^[0-9A-Za-z._-]+$/),definition=z.strictObject({expression:z.discriminatedUnion("type",[z.strictObject({type:z.literal("cron"),cron:z.string().min(1)}),z.strictObject({type:z.literal("single"),at:z.string().min(1)})]),timezone:z.string().min(1).max(50).optional(),jitter:z.number().int().min(1).max(15).optional(),target:z.strictObject({type:z.literal("queue"),topic:z.string().regex(/^[A-Za-z0-9_-]+$/)}),payload:z.unknown().optional()}),createBody=definition.extend({name:identifier.optional(),namespace:identifier.optional()}),updateBody=definition.partial().extend({jitter:definition.shape.jitter.nullable()}),scopeQuery=z.object({projectId:z.string().min(1).optional()}),identifierQuery=scopeQuery.extend({namespace:identifier.optional()}),listQuery=identifierQuery.extend({cursor:z.string().min(1).optional(),limit:z.coerce.number().int().min(1).max(100).default(20)}),MAX_PAYLOAD_BYTES=256*1024,MAX_BODY_BYTES=MAX_PAYLOAD_BYTES+16*1024;async function handleSchedulesRequest(broker,projectId,req,res,pathname){let send=(status,data)=>{res.writeHead(status,{"Content-Type":"application/json"}),res.end(JSON.stringify(data))},error2=(status,code,message2)=>send(status,{error:{code,message:message2}});try{let route=/^\/v1\/schedules(?:\/([^/]+)(?:\/(enable|disable|invoke))?)?$/.exec(pathname);if(!route){error2(404,"not_found","Schedule route not found");return}let[,encodedName,action]=route,methods=action?["POST"]:encodedName?["GET","PATCH","DELETE"]:["GET","POST"];if(!methods.includes(req.method||"")){res.setHeader("Allow",methods.join(", ")),error2(405,"method_not_allowed","Method not allowed");return}let query=Object.fromEntries(new URL(req.url||"/","http://localhost").searchParams),parsedQuery=(!encodedName&&req.method==="POST"?scopeQuery:identifierQuery).parse(query);if(parsedQuery.projectId!==void 0&&parsedQuery.projectId!==projectId)throw new import_local_schedules.ScheduleBrokerError("invalid_request","The projectId query parameter must match the local project.");if(!encodedName&&req.method==="GET"){let{namespace,cursor,limit}=listQuery.parse(query);send(200,broker.list({namespace,cursor,limit}));return}if(req.method==="PATCH"||!encodedName&&req.method==="POST"){let body;try{body=JSON.parse(await(0,import_raw_body.default)(req,{limit:MAX_BODY_BYTES,encoding:"utf8"}))}catch(err){let tooLarge=err.statusCode===413;error2(tooLarge?413:400,tooLarge?"payload_too_large":"bad_request",tooLarge?`Schedule request exceeds ${MAX_BODY_BYTES} bytes`:"Expected a JSON object as the request body");return}let parsed=(req.method==="PATCH"?updateBody:createBody).parse(body);if(parsed.payload!==void 0&&Buffer.byteLength(JSON.stringify(parsed.payload))>MAX_PAYLOAD_BYTES){error2(400,"payload_too_large",`Schedule payload exceeds ${MAX_PAYLOAD_BYTES} bytes`);return}encodedName?send(200,broker.update({name:identifier.parse(decodeURIComponent(encodedName)),namespace:identifierQuery.parse(query).namespace},parsed)):send(201,broker.create(createBody.parse(parsed)));return}let id={name:identifier.parse(decodeURIComponent(encodedName)),namespace:identifierQuery.parse(query).namespace};action==="invoke"?(await broker.invoke(id),res.writeHead(204),res.end()):action==="enable"||action==="disable"?send(200,broker[action](id)):req.method==="DELETE"?send(200,broker.delete(id)):send(200,broker.get(id))}catch(err){if(err instanceof z.ZodError)error2(400,"bad_request",err.issues.map(issue=>`${issue.path.join(".")||"request"}: ${issue.message}`).join("; "));else if(err instanceof URIError)error2(400,"bad_request","Invalid encoded schedule name");else if(err instanceof import_local_schedules.ScheduleBrokerError){let status={invalid_request:400,not_found:404,conflict:409,closed:503}[err.code],code={invalid_request:"bad_request",conflict:"schedule_already_exists",closed:"unavailable",not_found:"not_found"}[err.code];error2(status,code,err.message)}else error2(500,"schedule_dispatch_failed",err instanceof Error?err.message:"Failed to dispatch schedule")}}var import_build_utils8=__toESM(require_build_utils(),1);function collectStaticSchedules(authored,registry){let schedules=[...authored??[],...registry.schedules],error2=validateConfig({schedules});if(error2)throw error2;for(let schedule of registry.schedules)if("entrypoint"in schedule)throw new import_build_utils8.NowBuildError({code:"DEV_SCHEDULE_MANIFEST_ENTRYPOINT",message:`Native schedule "${(0,import_build_utils8.getScheduleName)(schedule)}" has an unresolved entrypoint. The builder's getDevManifest must return a Build Output API function or topic instead.`});let named=schedules.map(schedule=>({...schedule,name:(0,import_build_utils8.getScheduleName)(schedule)}));return named.sort((a,b)=>a.name.localeCompare(b.name)),named.map(schedule=>{let{name,timezone,jitter}=schedule;if("entrypoint"in schedule)throw new import_build_utils8.NowBuildError({code:"DEV_SCHEDULE_ENTRYPOINT_UNSUPPORTED",message:`Schedule "${name}" targets entrypoint "${schedule.entrypoint}", which vercel dev cannot resolve in a services project yet. Use function with an exact registered build output ID and a sole schedule/v1beta trigger, or topic for a queue.`});if("function"in schedule){let fn2=registry.functions.get(schedule.function);if(!fn2)throw dev.DEV_SCHEDULE_FUNCTION_MISSING({name,outputPath:schedule.function});if(fn2.experimentalTriggers?.length!==1||fn2.experimentalTriggers[0]?.type!=="schedule/v1beta")throw dev.DEV_SCHEDULE_FUNCTION_TRIGGER({name,outputPath:schedule.function})}return{name,expression:{type:"cron",cron:schedule.schedule},jitter,timezone,target:"function"in schedule?{type:"function",function:schedule.function}:"path"in schedule?{type:"path",path:schedule.path,...schedule.requestMethod!==void 0&&{requestMethod:schedule.requestMethod}}:{type:"queue",topic:schedule.topic}}})}import path3 from"path";function toOrchestratorService(sidecar){let{type:_type,...subscriber}=sidecar;return{...subscriber,schema:"experimentalServices",type:"worker",trigger:"queue"}}async function collectBuilderDevSidecars({builds,workPath,services=[]}){let builderSpecs=new Set(builds.map(build=>build.use)),buildersWithPkgs=await importBuilders(builderSpecs,workPath),servicesByBuilder=new Map(services.map(service=>[service.builder,service])),sidecars=(await Promise.all(builds.map(async build=>{let builder=buildersWithPkgs.get(build.use)?.builder;if(!builder)throw dev.DEV_BUILDER_LOAD_FAILED({use:build.use});let service=servicesByBuilder.get(build),serviceRoot=service?.root??".",sidecars2=await builder.getDevSidecars?.({workPath:path3.join(workPath,serviceRoot),build,...service?{service}:{}})??[];return service?sidecars2.map(sidecar=>({...sidecar,name:`${service.name}-${sidecar.name}`,workspace:serviceRoot})):sidecars2}))).flat(),names=new Set;for(let sidecar of sidecars){let{name,type}=sidecar;if(type!=="subscriber")throw dev.DEV_SIDECAR_UNSUPPORTED_TYPE({name,type});if(names.has(name))throw dev.DEV_SIDECAR_DUPLICATE_NAME({name});names.add(name)}return sidecars}function nodeHeadersToFetchHeaders(nodeHeaders){let headers=new globalThis.Headers;for(let[name,value]of Object.entries(nodeHeaders))if(Array.isArray(value))for(let val of value)headers.append(name,val);else typeof value<"u"&&headers.set(name,String(value));return headers}var NEVER_COMBINE_RESPONSE_HEADERS=new Set(["set-cookie","www-authenticate","proxy-authenticate"]),COMMA_JOIN_RESPONSE_HEADERS=new Set(["vary"]);function applyChainResponseHeader(res,name,value){if(NEVER_COMBINE_RESPONSE_HEADERS.has(name)){let existing=res.getHeader(name),values=Array.isArray(existing)?existing.map(String):existing!==void 0?[String(existing)]:[];values.push(value),res.setHeader(name,values);return}if(COMMA_JOIN_RESPONSE_HEADERS.has(name)){let existing=res.getHeader(name);res.setHeader(name,existing!==void 0?`${existing}, ${value}`:value);return}res.setHeader(name,value)}var NONOVERRIDABLE_HEADERS=new Set(["host","connection","content-length","transfer-encoding","keep-alive","transfer-encoding","te","upgrade","trailer"]);function applyOverriddenHeaders(reqHeaders,respHeaders){let headers=new globalThis.Headers(respHeaders),overriddenHeaders=headers.get("x-middleware-override-headers");if(!overriddenHeaders)return headers;let overriddenKeys=new Set;for(let key of overriddenHeaders.split(","))overriddenKeys.add(key.trim());headers.delete("x-middleware-override-headers");for(let key of Object.keys(reqHeaders))!NONOVERRIDABLE_HEADERS.has(key)&&!overriddenKeys.has(key)&&delete reqHeaders[key];for(let key of overriddenKeys.keys()){if(NONOVERRIDABLE_HEADERS.has(key))continue;let valueKey="x-middleware-request-"+key,newValue=headers.get(valueKey);reqHeaders[key]!==newValue&&(newValue?reqHeaders[key]=newValue:delete reqHeaders[key]),headers.delete(valueKey)}return headers}var import_error_utils=__toESM(require_dist(),1);import{parse}from"url";function parseListen(str,defaultPort=3e3){let port=Number(str);if(!isNaN(port))return[port];let url4=parse(str);switch(url4.protocol){case"pipe:":{let cutStr=str.replace(/^pipe:/,"");if(cutStr.slice(0,4)!=="\\\\.\\")throw dev.DEV_INVALID_WINDOWS_PIPE({endpoint:str});return[cutStr]}case"unix:":if(!url4.pathname)throw dev.DEV_INVALID_UNIX_SOCKET({endpoint:str});return[url4.pathname];case"tcp:":return url4.port=url4.port||String(defaultPort),[parseInt(url4.port,10),url4.hostname??void 0];default:if(!url4.slashes){if(url4.protocol===null)return[defaultPort,url4.pathname??void 0];if(port=Number(url4.hostname),url4.protocol&&!isNaN(port))return[port,url4.protocol.substring(0,url4.protocol.length-1)]}throw dev.DEV_INVALID_LISTEN_SCHEME({protocol:url4.protocol})}}function replaceLocalhost(address){return address.replace("[::]","localhost").replace("0.0.0.0","localhost")}import{lstat,readdir,readFile,stat}from"node:fs/promises";import{extname,isAbsolute as isAbsolute2,join as join3,relative as relative3,resolve}from"node:path";import{parse as parseUrl}from"node:url";var MAX_REDIRECTS=1e6,MAX_FILES=100,MAX_URL_LENGTH=2048,VALID_STATUS_CODES=new Set([301,302,303,307,308]),SUPPORTED_EXTENSIONS=new Set([".csv",".json",".jsonl"]),BulkRedirectTable=class{constructor(){this.caseSensitiveByHostPath=new Map;this.caseInsensitiveByHostPath=new Map;this.caseSensitiveByPath=new Map;this.caseInsensitiveByPath=new Map}get size(){return this.caseSensitiveByHostPath.size+this.caseInsensitiveByHostPath.size+this.caseSensitiveByPath.size+this.caseInsensitiveByPath.size}add(redirect2){let{host,pathname}=parseSource(redirect2.source),stored={destination:redirect2.destination,statusCode:redirect2.statusCode,preserveQueryParams:redirect2.preserveQueryParams};if(host){let key=hostPathKey(host,pathname);redirect2.caseSensitive?this.caseSensitiveByHostPath.set(key,stored):this.caseInsensitiveByHostPath.set(key.toLowerCase(),stored);return}redirect2.caseSensitive?this.caseSensitiveByPath.set(pathname,stored):this.caseInsensitiveByPath.set(pathname.toLowerCase(),stored)}lookup(pathname,host){let hostname=host?hostnameFromHostHeader(host):"";if(hostname){let hostKey=hostPathKey(hostname,pathname),hostMatch=this.caseSensitiveByHostPath.get(hostKey)||this.caseInsensitiveByHostPath.get(hostKey.toLowerCase());if(hostMatch)return hostMatch}return this.caseSensitiveByPath.get(pathname)||this.caseInsensitiveByPath.get(pathname.toLowerCase())}};async function getBulkRedirectsSignature(cwd,bulkRedirectsPath){if(!bulkRedirectsPath)return"";let resolved=resolveBulkRedirectsPath(cwd,bulkRedirectsPath);if(!resolved)return`invalid:${bulkRedirectsPath}`;try{let stats=await stat(resolved);if(stats.isFile())return`file:${resolved}:${stats.mtimeMs}:${stats.size}`;if(!stats.isDirectory())return`other:${resolved}:${stats.mtimeMs}`;let files=await listRedirectFiles(resolved),parts=await Promise.all(files.map(async file=>{try{let fileStats=await stat(file);return`${file}:${fileStats.mtimeMs}:${fileStats.size}`}catch{return`${file}:missing`}}));return`dir:${resolved}:${parts.join("|")}`}catch{return`missing:${resolved}`}}async function loadBulkRedirects(cwd,bulkRedirectsPath){let warnings=[],table=new BulkRedirectTable,resolved=resolveBulkRedirectsPath(cwd,bulkRedirectsPath);if(!resolved)return warnings.push(`Skipping bulk redirects path "${bulkRedirectsPath}" because it resolves outside the project directory.`),{table,redirectCount:0,fileCount:0,warnings};let files;try{let stats=await stat(resolved);if(stats.isDirectory())files=await listRedirectFiles(resolved),files.length>MAX_FILES&&(warnings.push(`Bulk redirects directory "${bulkRedirectsPath}" has ${files.length} files; only the first ${MAX_FILES} will be used.`),files=files.slice(0,MAX_FILES));else if(stats.isFile()){let ext=extname(resolved).toLowerCase();if(!SUPPORTED_EXTENSIONS.has(ext))return warnings.push(`Bulk redirects file "${bulkRedirectsPath}" must be a .csv, .json, or .jsonl file.`),{table,redirectCount:0,fileCount:0,warnings};files=[resolved]}else return warnings.push(`Bulk redirects path "${bulkRedirectsPath}" is not a file or directory.`),{table,redirectCount:0,fileCount:0,warnings}}catch(err){if(isNotFound(err))return warnings.push(`Bulk redirects path "${bulkRedirectsPath}" was not found.`),{table,redirectCount:0,fileCount:0,warnings};throw err}let redirectCount=0;for(let file of files){if(redirectCount>=MAX_REDIRECTS){warnings.push(`Bulk redirects limit of ${MAX_REDIRECTS} reached; remaining entries were skipped.`);break}let remaining=MAX_REDIRECTS-redirectCount,parsed=await parseRedirectFile(file,remaining,warnings,cwd);for(let redirect2 of parsed)table.add(redirect2),redirectCount++}let duplicateCount=redirectCount-table.size;return duplicateCount>0&&warnings.push(`Bulk redirects contain ${duplicateCount} duplicate ${duplicateCount===1?"source":"sources"}; the last occurrence wins.`),{table,redirectCount,fileCount:files.length,warnings}}function resolveBulkRedirect(table,reqUrl,host){let parsed=parseUrl(reqUrl),match=table.lookup(parsed.pathname||"/",host);if(!match)return;let location=match.destination;return match.preserveQueryParams&&parsed.search&&(location=appendQueryParams(location,parsed.search)),{location,statusCode:match.statusCode}}function appendQueryParams(destination,search){let query=search.startsWith("?")?search.slice(1):search;return query?destination.includes("?")?`${destination}&${query}`:`${destination}?${query}`:destination}function resolveBulkRedirectsPath(cwd,bulkRedirectsPath){let projectRoot=resolve(cwd),resolved=resolve(projectRoot,bulkRedirectsPath),relativeFromRoot=relative3(projectRoot,resolved);return relativeFromRoot.startsWith("..")||isAbsolute2(relativeFromRoot)?null:resolved}async function listRedirectFiles(dir){let files=[];return await walk(dir,files),files.sort(),files}async function walk(dir,files){let entries=await readdir(dir);for(let entry of entries){let fullPath=join3(dir,entry),stats=await lstat(fullPath);stats.isDirectory()?await walk(fullPath,files):stats.isFile()&&SUPPORTED_EXTENSIONS.has(extname(fullPath).toLowerCase())&&files.push(fullPath)}}async function parseRedirectFile(file,remaining,warnings,cwd){let rel=relative3(cwd,file)||file,ext=extname(file).toLowerCase(),content;try{content=stripBom(await readFile(file,"utf8"))}catch(err){return warnings.push(`Failed to read bulk redirects file "${rel}": ${errorMessage(err)}`),[]}try{return ext===".csv"?parseCsvRedirects(content,remaining,warnings,rel):ext===".jsonl"?parseJsonlRedirects(content,remaining,warnings,rel):parseJsonRedirects(content,remaining,warnings,rel)}catch(err){return warnings.push(`Failed to parse bulk redirects file "${rel}": ${errorMessage(err)}`),[]}}function parseJsonRedirects(content,remaining,warnings,rel){let parsed=JSON.parse(content);return Array.isArray(parsed)?normalizeRedirects(parsed,remaining,warnings,rel):(warnings.push(`Bulk redirects file "${rel}" must contain a JSON array of redirects.`),[])}function parseJsonlRedirects(content,remaining,warnings,rel){let rows=[],lines=content.split(/\r?\n/);for(let i=0;i<lines.length;i++){let line=lines[i].trim();if(line)try{rows.push(JSON.parse(line))}catch{warnings.push(`Skipping invalid JSONL in "${rel}" at line ${i+1}.`)}}return normalizeRedirects(rows,remaining,warnings,rel)}var CSV_HEADER_ALIASES={source:"source",destination:"destination",permanent:"permanent",statuscode:"statusCode",casesensitive:"caseSensitive",preservequeryparams:"preserveQueryParams"};function parseCsvRedirects(content,remaining,warnings,rel){let lines=content.split(/\r?\n/).filter(line=>line.trim().length>0);if(lines.length===0)return warnings.push(`Bulk redirects CSV "${rel}" is empty.`),[];let headers=parseCsvLine(lines[0]).map(header=>CSV_HEADER_ALIASES[header.trim().toLowerCase()]);if(!headers.includes("source")||!headers.includes("destination"))return warnings.push(`Bulk redirects CSV "${rel}" must have "source" and "destination" columns.`),[];let rows=[];for(let i=1;i<lines.length;i++){let values=parseCsvLine(lines[i]),row={};for(let col=0;col<headers.length;col++){let header=headers[col];header&&(row[header]=values[col]??"")}rows.push(row)}return normalizeRedirects(rows,remaining,warnings,rel)}function normalizeRedirects(rows,remaining,warnings,rel){let redirects=[];for(let i=0;i<rows.length;i++){if(redirects.length>=remaining){warnings.push(`Bulk redirects limit of ${MAX_REDIRECTS} reached while reading "${rel}"; remaining entries were skipped.`);break}let row=rows[i];if(!row||typeof row!="object"){warnings.push(`Skipping invalid redirect in "${rel}" at index ${i}.`);continue}let record=row,source=asTrimmedString(record.source),destination=asTrimmedString(record.destination);if(!source||!destination){warnings.push(`Skipping redirect in "${rel}" at index ${i}: source and destination are required.`);continue}if(source.length>MAX_URL_LENGTH||destination.length>MAX_URL_LENGTH){warnings.push(`Skipping redirect in "${rel}" at index ${i}: source and destination must be at most ${MAX_URL_LENGTH} characters.`);continue}let statusCode;if(record.statusCode!==void 0&&record.statusCode!==""){let parsedStatus=parseStatusCode(record.statusCode);if(parsedStatus===void 0){warnings.push(`Skipping redirect in "${rel}" at index ${i}: statusCode must be one of ${[...VALID_STATUS_CODES].join(", ")}.`);continue}statusCode=parsedStatus}else statusCode=parseBoolean(record.permanent)??!1?308:307;redirects.push({source,destination,statusCode,caseSensitive:parseBoolean(record.caseSensitive)??!1,preserveQueryParams:parseBoolean(record.preserveQueryParams)??!1})}return redirects}function parseSource(source){if(/^https?:\/\//i.test(source))try{let parsed=new URL(source);return{host:parsed.hostname.toLowerCase(),pathname:parsed.pathname||"/"}}catch{return{host:null,pathname:source}}return{host:null,pathname:source||"/"}}function hostPathKey(host,pathname){return`${host}\0${pathname}`}function hostnameFromHostHeader(hostHeader){let trimmed=hostHeader.trim();if(!trimmed)return"";if(trimmed.startsWith("[")){let end=trimmed.indexOf("]");return end===-1?trimmed.toLowerCase():trimmed.slice(1,end).toLowerCase()}let colon=trimmed.lastIndexOf(":");return colon!==-1&&trimmed.indexOf(":")===colon?trimmed.slice(0,colon).toLowerCase():trimmed.toLowerCase()}function parseBoolean(value){if(typeof value=="boolean")return value;if(typeof value=="number")return value===1?!0:value===0?!1:void 0;if(typeof value!="string")return;let normalized=value.trim().toLowerCase();if(normalized==="t"||normalized==="true")return!0;if(normalized==="f"||normalized==="false")return!1}function parseStatusCode(value){let n=typeof value=="number"?value:typeof value=="string"?Number(value.trim()):NaN;return VALID_STATUS_CODES.has(n)?n:void 0}function asTrimmedString(value){if(typeof value!="string")return;let trimmed=value.trim();return trimmed||void 0}function parseCsvLine(line){let fields=[],current="",inQuotes=!1;for(let i=0;i<line.length;i++){let char=line[i];inQuotes?char==='"'?line[i+1]==='"'?(current+='"',i++):inQuotes=!1:current+=char:char==='"'?inQuotes=!0:char===","?(fields.push(current),current=""):current+=char}return fields.push(current),fields}function stripBom(content){return content.charCodeAt(0)===65279?content.slice(1):content}function isNotFound(err){return typeof err=="object"&&err!==null&&"code"in err&&err.code==="ENOENT"}function errorMessage(err){return err instanceof Error?err.message:String(err)}var DEV_SERVER_PORT_BIND_TIMEOUT=(0,import_ms6.default)("5m"),DEV_QUEUES_DEFAULT_VISIBILITY_TIMEOUT_SECONDS=60,DEV_RUNTIME_CACHE_MAX_ITEM_SIZE=2*1024*1024,DEV_RUNTIME_CACHE_ONE_YEAR_SECONDS=31536e3,frameworkRuntimeSet=new Set(import_frameworks3.frameworkList.map(f=>f.useRuntime?.use||"@vercel/static-build"));function isApiDirBuild(build){let src=build.src?.replace(/^\.\//,"");return typeof src=="string"&&src.startsWith("api/")}function sortBuilders(buildA,buildB){return buildA&&buildA.use&&(0,import_fs_detectors2.isOfficialRuntime)("static-build",buildA.use)?1:buildB&&buildB.use&&(0,import_fs_detectors2.isOfficialRuntime)("static-build",buildB.use)?-1:0}var DevServer=class{constructor(cwd,options){this.initialDevCommandStarted=!1;this.devCommandStarts=new Set;this.functionDispatchReady=!1;this.functionReconciliations=0;this.configGeneration=0;this.unmatchedQueuePatterns=new Set;this.functionRegistry={functions:new Map,schedules:[],unmatchedPatterns:[]};this.responseTransformsByReq=new WeakMap;this.shouldBuildInDev=build=>{if(build.config?.scheduleFunction||!this.shouldUseServicesOrchestrator()&&isApiDirBuild(build))return!0;let{name}=(0,import_npm_package_arg.default)(build.use);return!frameworkRuntimeSet.has(name||"")};this.clearVercelConfigPromise=()=>{this.getVercelConfigPromise=null};this.getExtensionlessFile=path6=>{let ext=extname2(path6);return this.apiDir&&path6.startsWith(this.apiDir+"/")&&this.apiExtensions.has(ext)?path6.slice(0,-ext.length):null};this.devServerHandler=async(req,res)=>{if(await this.handleSchedulesProxyRequest(req,res))return;try{await this.startPromise}catch{res.destroy();return}let requestId=generateRequestId(this.podId);if(this.stopping){res.setHeader("Connection","close"),await this.send404(req,res,requestId);return}let method=req.method||"GET";output_manager_default.debug(`${import_chalk2.default.bold(method)} ${req.url}`);try{let vercelConfig=await this.getVercelConfig();await this.serveProjectAsNowV2(req,res,requestId,vercelConfig)}catch(err){console.error(err),(0,import_error_utils.isError)(err)&&typeof err.stack=="string"&&output_manager_default.debug(err.stack),res.finished||(res.statusCode=500,res.end((0,import_error_utils.errorToString)(err)))}};this.handleSchedulesRoute=async(req,res,pathname)=>{let session=this.schedulesSession?.session;if(this.stopping||!session&&req.method==="GET"&&pathname==="/v1/info"){res.writeHead(503,{"content-type":"application/json"}),res.end(JSON.stringify({error:{code:"local_session_unavailable",message:"Local Schedules is not ready or is stopping. Wait for vercel dev to start and try again."}}));return}if(req.headers[LOCAL_SCHEDULES_SESSION_HEADER]!==void 0&&req.headers[LOCAL_SCHEDULES_SESSION_HEADER]!==session?.id){res.writeHead(409,{"content-type":"application/json"}),res.end(JSON.stringify({error:{code:"local_session_mismatch",message:"The local Schedules session has changed. Run the command again to discover the current session."}}));return}if(req.method==="GET"&&pathname==="/v1/info"){res.writeHead(200,{"content-type":"application/json"}),res.end(JSON.stringify(session));return}await handleSchedulesRequest(this.scheduleBroker,this.projectId??"prj_local",req,res,pathname)};this.exitWithStatus=async(match,routeResult,phase,req,res,requestId,responseTransforms)=>{let{status,headers,dest}=routeResult,location=headers.location||dest;if(status&&location&&300<=status&&status<=399)return output_manager_default.debug(`Route found with redirect status code ${status}`),await this.sendRedirect(req,res,requestId,location,status,responseTransforms),!0;if(!match&&status&&phase!=="miss"){if(routeResult.userDest)return!1;output_manager_default.debug(`Route found with with status code ${status}`);let errorHeaders={...headers};return responseTransforms&&applyResponseTransforms(errorHeaders,responseTransforms),await this.sendError(req,res,requestId,"",status,errorHeaders),!0}return!1};this.handleQueuesRoute=async(req,res,pathname)=>{if(!this.queueBroker){res.writeHead(503),res.end("Queues broker not initialized");return}if(!pathname.startsWith(DEV_QUEUE_API_PREFIX)){res.writeHead(404),res.end("Not Found");return}let topicPath=pathname.slice(DEV_QUEUE_API_PREFIX.length),sendMatch=topicPath.match(/^([A-Za-z0-9_-]+)$/);if(req.method==="POST"&&sendMatch){let topic=sendMatch[1],contentType2=req.headers["content-type"]||"application/json",payload=await(0,import_raw_body2.default)(req),retentionHeader=req.headers["vqs-retention-seconds"],retentionSeconds=retentionHeader&&!isNaN(parseInt(retentionHeader,10))?parseInt(retentionHeader,10):void 0,delayHeader=req.headers["vqs-delay-seconds"],delaySeconds=delayHeader&&!isNaN(parseInt(delayHeader,10))?parseInt(delayHeader,10):void 0,idempotencyKey=req.headers["vqs-idempotency-key"],{messageId}=this.queueBroker.enqueue(topic,payload,contentType2,{retentionSeconds,delaySeconds,idempotencyKey});res.writeHead(201,{"Content-Type":"application/json","Vqs-Message-Id":messageId}),res.end(JSON.stringify({messageId}));return}let receiveByIdMatch=topicPath.match(/^([A-Za-z0-9_-]+)\/consumer\/([A-Za-z0-9_-]+)\/id\/([^/]+)$/);if(req.method==="POST"&&receiveByIdMatch){let[,queueName,consumer,messageId]=receiveByIdMatch,originalMessageId=this.queueBroker.getOriginalMessageIdForDuplicate(queueName,messageId);if(originalMessageId){res.writeHead(409,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"This messageId was a duplicate - use originalMessageId instead",originalMessageId}));return}let result=this.queueBroker.receiveById(queueName,messageId,consumer);if(!result){res.writeHead(404),res.end("Message not found");return}let boundary=`----vcdevboundary${randomBytes2(8).toString("hex")}`,partHeaders=[`Vqs-Message-Id: ${messageId}`,`Vqs-Delivery-Count: ${result.deliveryCount}`,`Vqs-Timestamp: ${result.createdAt}`,`Vqs-Receipt-Handle: ${result.receiptHandle}`,`Content-Type: ${result.contentType}`].join(`\r
42
42
  `),body=Buffer.concat([Uint8Array.from(Buffer.from(`--${boundary}\r
43
43
  ${partHeaders}\r
44
44
  \r
@@ -52,20 +52,20 @@ ${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")}};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.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=createErrorReporter(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.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");return{queues:{direct:this.queueOrigin,proxy:`${this.address.origin}${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`},runtimeCache:{direct:`${this.runtimeCacheOrigin}${DEV_RUNTIME_CACHE_API_PREFIX}`,proxy:`${this.address.origin}${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}${DEV_RUNTIME_CACHE_API_PREFIX}`},...this.schedulesOrigin?{schedules:{direct:this.schedulesOrigin,proxy:`${this.address.origin}${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)}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-NBX5UWHW.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.schedules?.map(import_build_utils9.parseScheduleDefinition),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};if(Object.keys(allEnv).length===0){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.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(!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=null;for(;typeof address!="string";)try{address=(await(0,import_async_listen.listen)(this.server,...listenSpec)).toString()}catch(err){if((0,import_error_utils.isErrnoException)(err))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}this._address=new URL2(replaceLocalhost(address)),this.runtimeCache=new RuntimeCacheStore;let runtimeCacheListener=await 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].filter(port=>port!==void 0&&port!==0)});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
- External clients configured for ${runtimeCacheListener.defaultPort} will not reach this dev server. Pin a port with --runtime-cache-port.`);let queueListener=await listenOnDevResourcePort(this.queueServer,{name:"Vercel Queues",flag:"--queue-port",defaultPort:DEV_QUEUE_DEFAULT_PORT,port:this.queuePort,reservedPorts:[this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT]});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
- 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 listenOnDevResourcePort(this.schedulesServer,{name:"Vercel Schedules",flag:"--schedules-port",defaultPort:DEV_SCHEDULES_DEFAULT_PORT,port:this.schedulesPort});this.schedulesOrigin=schedulesListener.origin,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.
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")}};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.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=createErrorReporter(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");return{queues:{direct:this.queueOrigin,proxy:`${this.address.origin}${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`},runtimeCache:{direct:`${this.runtimeCacheOrigin}${DEV_RUNTIME_CACHE_API_PREFIX}`,proxy:`${this.address.origin}${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}${DEV_RUNTIME_CACHE_API_PREFIX}`},...this.schedulesOrigin?{schedules:{direct:this.schedulesOrigin,proxy:`${this.address.origin}${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)}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-YCLXPL5H.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};if(Object.keys(allEnv).length===0){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.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=null;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 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].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
+ 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]}));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
+ 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}));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.
59
- `));let vercelConfig=await this.getVercelConfig(),devCommandPromise,startDevCommand=()=>{this.initialDevCommandStarted=!0,devCommandPromise=this.runDevCommand(),devCommandPromise.catch(()=>{})};if(this.shouldUseServicesOrchestrator()){let orchestratorServices=[...this.services||[],...(this.sidecars||[]).map(toOrchestratorService)];this.orchestrator=new ServicesOrchestrator({services:orchestratorServices,cwd:this.cwd,repoRoot:this.repoRoot,env:this.envConfigs.allEnv,proxyOrigin:this.address.origin,resourceEndpoints:this.resourceEndpoints,useImplicitEnvInjection:this.useImplicitServicesEnvInjection,onQueueSubscriptions:(serviceName,subscriptions)=>this.queueBroker?.updateServiceSubscriptions(serviceName,subscriptions)});let queueServices=orchestratorServices.filter(import_build_utils9.isExperimentalService).filter(import_build_utils9.isQueueBackedService);this.queueBroker.registerServices(queueServices),devCommandPromise=this.orchestrator.startAll(),this.devProcessOrigin=void 0;let addressFormatted=this.address.toString();this.address.pathname==="/"&&this.address.protocol==="http:"&&(addressFormatted=addressFormatted.replace(/\/$/,"")),output_manager_default.print(`${import_chalk2.default.cyan(">")} Available at:
59
+ `));let vercelConfig=await this.getVercelConfig();if(this.stopping)return;let devCommandPromise,startDevCommand=()=>{this.initialDevCommandStarted=!0,devCommandPromise=this.runDevCommand(),devCommandPromise.catch(()=>{})};if(this.shouldUseServicesOrchestrator()){let orchestratorServices=[...this.services||[],...(this.sidecars||[]).map(toOrchestratorService)];this.orchestrator=new ServicesOrchestrator({services:orchestratorServices,cwd:this.cwd,repoRoot:this.repoRoot,env:this.envConfigs.allEnv,proxyOrigin:this.address.origin,resourceEndpoints:this.resourceEndpoints,useImplicitEnvInjection:this.useImplicitServicesEnvInjection,onQueueSubscriptions:(serviceName,subscriptions)=>this.queueBroker?.updateServiceSubscriptions(serviceName,subscriptions)});let queueServices=orchestratorServices.filter(import_build_utils9.isExperimentalService).filter(import_build_utils9.isQueueBackedService);this.queueBroker.registerServices(queueServices),devCommandPromise=this.orchestrator.startAll(),this.devProcessOrigin=void 0;let addressFormatted=this.address.toString();this.address.pathname==="/"&&this.address.protocol==="http:"&&(addressFormatted=addressFormatted.replace(/\/$/,"")),output_manager_default.print(`${import_chalk2.default.cyan(">")} Available at:
60
60
  `);let v1WebServices=(this.services||[]).filter(import_build_utils9.isExperimentalService).filter(service=>service.type==="web");if(v1WebServices.length>0)for(let service of v1WebServices){let servicePath=service.routePrefix||"/",serviceUrl=`${addressFormatted}${servicePath==="/"?"":servicePath}`;output_manager_default.print(` ${import_chalk2.default.bold(service.name)}: ${link_default(serviceUrl)}
61
61
  `)}else output_manager_default.print(` ${link_default(addressFormatted)}
62
- `)}else this.hasSubscribers()||startDevCommand();let files=await staticFiles(this.cwd,{});this.files={};for(let fsPath of files){let path6=relative2(this.cwd,fsPath),{mode}=await import_fs_extra.default.stat(fsPath);this.files[path6]=new import_build_utils9.FileFsRef({mode,fsPath});let extensionless=this.getExtensionlessFile(path6);extensionless&&(this.files[extensionless]=new import_build_utils9.FileFsRef({mode,fsPath}))}await this.updateBuildMatches(vercelConfig,!0),await this.setupBuilderDevSidecars(),!this.shouldUseServicesOrchestrator()&&!devCommandPromise&&startDevCommand();let blockingBuilds=Array.from(this.buildMatches.values()).filter(needsBlockingBuild);if(blockingBuilds.length>0){output_manager_default.log(`Creating initial ${(0,import_pluralize2.default)("build",blockingBuilds.length)}`);for(let match of blockingBuilds)await executeBuild(vercelConfig,this,this.files,match,null,!0);output_manager_default.success("Build completed")}if(await import_fs_extra.default.mkdirp(this.devCacheDir),this.watcher=watch(this.cwd,{ignored:fsPath=>this.isWatcherIgnored(fsPath),ignoreInitial:!0,usePolling:!1,persistent:!0}),this.watcher.on("add",path6=>{this.enqueueFsEvent("add",path6)}),this.watcher.on("change",path6=>{this.enqueueFsEvent("change",path6)}),this.watcher.on("unlink",path6=>{this.enqueueFsEvent("unlink",path6)}),this.watcher.on("error",err=>{output_manager_default.error(`Watcher error: ${err}`)}),await(0,import_once.default)(this.watcher,"ready"),this.server.on("upgrade",async(req,socket,head)=>{if(await this.startPromise,this.orchestrator||this.sidecarOrchestrator){let pathname2=url3.parse(req.url||"/").pathname||"/",service=this.orchestrator?.getServiceForRoute(pathname2)||this.sidecarOrchestrator?.getServiceForRoute(pathname2);if(service){let target=`http://${service.host}:${service.port}`;output_manager_default.debug(`Detected "upgrade" event, proxying to service "${service.name}" at ${target}`),this.proxy.ws(req,socket,head,{target});return}if(this.orchestrator){let vercelConfig2=await this.getVercelConfig();if(vercelConfig2.experimentalServicesV2||vercelConfig2.services){let routeResult=await devRouter(req.url||"/",req.method,vercelConfig2.routes,this,vercelConfig2);if(isServiceDestination(routeResult.matched_route)){let{service:serviceName}=routeResult.matched_route.destination,origin=this.orchestrator.getServiceOrigin(serviceName);if(origin){output_manager_default.debug(`Detected "upgrade" event, proxying to service "${serviceName}" at ${origin}`),this.proxy.ws(req,socket,head,{target:origin});return}}}output_manager_default.debug(`Detected "upgrade" event, but no matching service found for ${pathname2}`),socket.destroy();return}}if(this.devProcessOrigin){let target=this.devProcessOrigin;output_manager_default.debug(`Detected "upgrade" event, proxying to ${target}`),this.proxy.ws(req,socket,head,{target});return}let pathname=url3.parse(req.url||"/").pathname||"/";for(let match of this.buildMatches.values()){let{builder}=match.builderWithPkg;if(typeof builder.startDevServer=="function")try{let result=await builder.startDevServer({files:this.files,entrypoint:match.entrypoint,workPath:this.cwd,config:match.config||{},repoRootPath:this.repoRoot,meta:{isDev:!0,...this.getDevResourceMeta(),requestPath:pathname,devCacheDir:this.devCacheDir,...this.getSidecarDevMeta(match),env:this.getBuilderDevEnv(match,this.envConfigs.runEnv),buildEnv:{...this.envConfigs.buildEnv}}});if(result){let{port,pid,shutdown}=result;this.shutdownCallbacks.set(pid,shutdown);let target=`http://127.0.0.1:${port}`;output_manager_default.debug(`Detected "upgrade" event, proxying to builder dev server at ${target}`),this.proxy.ws(req,socket,head,{target});return}}catch(err){output_manager_default.debug(`Failed to start dev server for upgrade: ${err}`)}}output_manager_default.debug(`Detected "upgrade" event, but no backend available for ${pathname}`),socket.destroy()}),await devCommandPromise,!this.stopping&&(this.functionDispatchReady=!0,this.scheduleBroker.start(),output_manager_default.log("Local resources:"),printAlignedLabel("Vercel Queues",link_default(this.queueOrigin)),printAlignedLabel("Vercel Schedules",link_default(this.schedulesOrigin)),printAlignedLabel("Runtime Cache",link_default(this.resourceEndpoints.runtimeCache.direct)),!this.orchestrator?.hasServices())){let addressFormatted=this.address.toString();this.address.pathname==="/"&&this.address.protocol==="http:"&&(addressFormatted=addressFormatted.replace(/\/$/,"")),output_manager_default.ready(`Available at ${link_default(addressFormatted)}`)}}async stop(_exitCode){if(this.stopping)return;this.stopping=!0,this.devProcessOrigin=void 0,await this.scheduleBroker.close();let{devProcess}=this,{debug}=output_manager_default,ops=[];for(let match of this.buildMatches.values())ops.push(shutdownBuilder(match));if(devProcess?.pid&&ops.push(treeKill(devProcess.pid)),ops.push(...Array.from(this.devCommandStarts,start=>start.catch(()=>{}))),this.orchestrator&&ops.push(this.orchestrator.stopAll()),this.sidecarOrchestrator&&ops.push(this.sidecarOrchestrator.stopAll()),this.queueBroker&&this.queueBroker.stop(),this.runtimeCache&&(this.runtimeCache.stop(),this.runtimeCache=void 0),ops.push(close(this.queueServer)),ops.push(close(this.runtimeCacheServer)),ops.push(close(this.schedulesServer)),ops.push(close(this.server)),this.watcher){debug("Closing file watcher");let closePromise=this.watcher.close();closePromise&&ops.push(closePromise)}for(let pid of this.shutdownCallbacks.keys())ops.push(this.killBuilderDevServer(pid));await Promise.all(ops),this.devProcess=void 0,this.devCommandEnv=void 0,this.currentDevCommand=void 0}async killBuilderDevServer(pid){let{debug}=output_manager_default;debug(`Killing builder dev server with PID ${pid}`);let shutdownCb=this.shutdownCallbacks.get(pid);if(this.shutdownCallbacks.delete(pid),shutdownCb){debug(`Running shutdown callback for PID ${pid}`),await shutdownCb();return}try{await treeKill(pid),debug(`Killed builder dev server with PID ${pid}`)}catch(err){debug(`Failed to kill builder dev server with PID ${pid}: ${err}`)}}async send404(req,res,requestId){return this.sendError(req,res,requestId,"NOT_FOUND",404)}async sendError(req,res,requestId,errorCode,statusCode=500,headers={}){res.statusCode=statusCode,this.setResponseHeaders(res,requestId,headers);let http_status_description=generateHttpStatusDescription(statusCode),error_code=errorCode||http_status_description,errorMessage2=generateErrorMessage(statusCode,error_code),body,{accept="text/plain"}=req.headers;if(accept.includes("json"))res.setHeader("content-type","application/json"),body=`${JSON.stringify({error:{code:statusCode,message:errorMessage2.title}})}
62
+ `)}else this.hasSubscribers()||startDevCommand();let files=await staticFiles(this.cwd,{});this.files={};for(let fsPath of files){let path6=relative2(this.cwd,fsPath),{mode}=await import_fs_extra.default.stat(fsPath);this.files[path6]=new import_build_utils9.FileFsRef({mode,fsPath});let extensionless=this.getExtensionlessFile(path6);extensionless&&(this.files[extensionless]=new import_build_utils9.FileFsRef({mode,fsPath}))}await this.updateBuildMatches(vercelConfig,!0),await this.setupBuilderDevSidecars(),!this.shouldUseServicesOrchestrator()&&!devCommandPromise&&startDevCommand();let blockingBuilds=Array.from(this.buildMatches.values()).filter(needsBlockingBuild);if(blockingBuilds.length>0){output_manager_default.log(`Creating initial ${(0,import_pluralize2.default)("build",blockingBuilds.length)}`);for(let match of blockingBuilds)await executeBuild(vercelConfig,this,this.files,match,null,!0);output_manager_default.success("Build completed")}if(await import_fs_extra.default.mkdirp(this.devCacheDir),this.watcher=watch(this.cwd,{ignored:fsPath=>this.isWatcherIgnored(fsPath),ignoreInitial:!0,usePolling:!1,persistent:!0}),this.watcher.on("add",path6=>{this.enqueueFsEvent("add",path6)}),this.watcher.on("change",path6=>{this.enqueueFsEvent("change",path6)}),this.watcher.on("unlink",path6=>{this.enqueueFsEvent("unlink",path6)}),this.watcher.on("error",err=>{output_manager_default.error(`Watcher error: ${err}`)}),await(0,import_once.default)(this.watcher,"ready"),this.server.on("upgrade",async(req,socket,head)=>{if(await this.startPromise,this.orchestrator||this.sidecarOrchestrator){let pathname2=url3.parse(req.url||"/").pathname||"/",service=this.orchestrator?.getServiceForRoute(pathname2)||this.sidecarOrchestrator?.getServiceForRoute(pathname2);if(service){let target=`http://${service.host}:${service.port}`;output_manager_default.debug(`Detected "upgrade" event, proxying to service "${service.name}" at ${target}`),this.proxy.ws(req,socket,head,{target});return}if(this.orchestrator){let vercelConfig2=await this.getVercelConfig();if(vercelConfig2.experimentalServicesV2||vercelConfig2.services){let routeResult=await devRouter(req.url||"/",req.method,vercelConfig2.routes,this,vercelConfig2);if(isServiceDestination(routeResult.matched_route)){let{service:serviceName}=routeResult.matched_route.destination,origin=this.orchestrator.getServiceOrigin(serviceName);if(origin){output_manager_default.debug(`Detected "upgrade" event, proxying to service "${serviceName}" at ${origin}`),this.proxy.ws(req,socket,head,{target:origin});return}}}output_manager_default.debug(`Detected "upgrade" event, but no matching service found for ${pathname2}`),socket.destroy();return}}if(this.devProcessOrigin){let target=this.devProcessOrigin;output_manager_default.debug(`Detected "upgrade" event, proxying to ${target}`),this.proxy.ws(req,socket,head,{target});return}let pathname=url3.parse(req.url||"/").pathname||"/";for(let match of this.buildMatches.values()){let{builder}=match.builderWithPkg;if(typeof builder.startDevServer=="function")try{let result=await builder.startDevServer({files:this.files,entrypoint:match.entrypoint,workPath:this.cwd,config:match.config||{},repoRootPath:this.repoRoot,meta:{isDev:!0,...this.getDevResourceMeta(),requestPath:pathname,devCacheDir:this.devCacheDir,...this.getSidecarDevMeta(match),env:this.getBuilderDevEnv(match,this.envConfigs.runEnv),buildEnv:{...this.envConfigs.buildEnv}}});if(result){let{port,pid,shutdown}=result;this.shutdownCallbacks.set(pid,shutdown);let target=`http://127.0.0.1:${port}`;output_manager_default.debug(`Detected "upgrade" event, proxying to builder dev server at ${target}`),this.proxy.ws(req,socket,head,{target});return}}catch(err){output_manager_default.debug(`Failed to start dev server for upgrade: ${err}`)}}output_manager_default.debug(`Detected "upgrade" event, but no backend available for ${pathname}`),socket.destroy()}),await devCommandPromise,!this.stopping&&(this.functionDispatchReady=!0,this.scheduleBroker.start(),output_manager_default.log("Local resources:"),printAlignedLabel("Vercel Queues",link_default(this.queueOrigin)),printAlignedLabel("Vercel Schedules",link_default(this.schedulesOrigin)),printAlignedLabel("Runtime Cache",link_default(this.resourceEndpoints.runtimeCache.direct)),!this.orchestrator?.hasServices())){let addressFormatted=this.address.toString();this.address.pathname==="/"&&this.address.protocol==="http:"&&(addressFormatted=addressFormatted.replace(/\/$/,"")),output_manager_default.ready(`Available at ${link_default(addressFormatted)}`)}}stop(_exitCode){return this.stopPromise||(this.stopPromise=this._stop()),this.stopPromise}async _stop(){this.stopping=!0,this.devProcessOrigin=void 0,await this.listenerStartup?.catch(()=>{}),await this.schedulesSessionPublication?.catch(()=>{}),await this.scheduleBroker.close();let{devProcess}=this,{debug}=output_manager_default,ops=[];this.schedulesSession&&(ops.push(this.schedulesSession.dispose()),this.schedulesSession=void 0);for(let match of this.buildMatches.values())ops.push(shutdownBuilder(match));if(devProcess?.pid&&ops.push(treeKill(devProcess.pid)),ops.push(...Array.from(this.devCommandStarts,start=>start.catch(()=>{}))),this.orchestrator&&ops.push(this.orchestrator.stopAll()),this.sidecarOrchestrator&&ops.push(this.sidecarOrchestrator.stopAll()),this.queueBroker&&this.queueBroker.stop(),this.runtimeCache&&(this.runtimeCache.stop(),this.runtimeCache=void 0),ops.push(close(this.queueServer)),ops.push(close(this.runtimeCacheServer)),ops.push(close(this.schedulesServer)),ops.push(close(this.server)),this.functionDispatchReady||this.server.closeAllConnections(),this.watcher){debug("Closing file watcher");let closePromise=this.watcher.close();closePromise&&ops.push(closePromise)}for(let pid of this.shutdownCallbacks.keys())ops.push(this.killBuilderDevServer(pid));await Promise.all(ops),this.devProcess=void 0,this.devCommandEnv=void 0,this.currentDevCommand=void 0}async killBuilderDevServer(pid){let{debug}=output_manager_default;debug(`Killing builder dev server with PID ${pid}`);let shutdownCb=this.shutdownCallbacks.get(pid);if(this.shutdownCallbacks.delete(pid),shutdownCb){debug(`Running shutdown callback for PID ${pid}`),await shutdownCb();return}try{await treeKill(pid),debug(`Killed builder dev server with PID ${pid}`)}catch(err){debug(`Failed to kill builder dev server with PID ${pid}: ${err}`)}}async send404(req,res,requestId){return this.sendError(req,res,requestId,"NOT_FOUND",404)}async sendError(req,res,requestId,errorCode,statusCode=500,headers={}){res.statusCode=statusCode,this.setResponseHeaders(res,requestId,headers);let http_status_description=generateHttpStatusDescription(statusCode),error_code=errorCode||http_status_description,errorMessage2=generateErrorMessage(statusCode,error_code),body,{accept="text/plain"}=req.headers;if(accept.includes("json"))res.setHeader("content-type","application/json"),body=`${JSON.stringify({error:{code:statusCode,message:errorMessage2.title}})}
63
63
  `;else if(accept.includes("html")){res.setHeader("content-type","text/html; charset=utf-8");let view;statusCode===404?view=error_404({...errorMessage2,http_status_code:statusCode,http_status_description,error_code,request_id:requestId}):statusCode===502?view=error_502({...errorMessage2,http_status_code:statusCode,http_status_description,error_code,request_id:requestId}):view=error({http_status_code:statusCode,http_status_description,error_code,request_id:requestId}),body=error_base({http_status_code:statusCode,http_status_description,view})}else res.setHeader("content-type","text/plain; charset=utf-8"),body=`${errorMessage2.title}
64
64
 
65
65
  ${error_code}
66
66
  `;res.end(body)}async sendRedirect(req,res,requestId,location,statusCode=302,responseTransforms){output_manager_default.debug(`Redirect ${statusCode}: ${location}`),res.statusCode=statusCode;let redirectHeaders={location};responseTransforms&&applyResponseTransforms(redirectHeaders,responseTransforms),this.setResponseHeaders(res,requestId,redirectHeaders);let body,{accept="text/plain"}=req.headers;accept.includes("json")?(res.setHeader("content-type","application/json"),body=`${JSON.stringify({redirect:location,status:String(statusCode)})}
67
67
  `):accept.includes("html")?(res.setHeader("content-type","text/html; charset=utf-8"),body=redirect({location,statusCode})):(res.setHeader("content-type","text/plain; charset=utf-8"),body=`Redirecting...
68
- `),res.end(body)}getRequestIp(req){return req.connection.remoteAddress||"127.0.0.1"}setResponseHeaders(res,requestId,headers={}){let allHeaders={"cache-control":"public, max-age=0, must-revalidate",...headers,server:"Vercel","x-vercel-id":requestId,"x-vercel-cache":"MISS"};for(let[name,value]of Object.entries(allHeaders))res.setHeader(name,value)}prepareTransforms(req,requestTransforms,responseTransforms){requestTransforms&&requestTransforms.length>0&&applyRequestTransforms(req,requestTransforms),responseTransforms&&hasResponseTransforms(responseTransforms)&&this.responseTransformsByReq.set(req,responseTransforms)}clearResponseTransforms(req){this.responseTransformsByReq.delete(req)}getProxyHeaders(req,requestId,xfwd){let ip=this.getRequestIp(req),{host}=req.headers,headers={connection:"close","x-real-ip":ip,"x-vercel-deployment-url":host,"x-vercel-forwarded-for":ip,"x-vercel-id":requestId};return xfwd&&(headers["x-forwarded-host"]=host,headers["x-forwarded-proto"]="http",headers["x-forwarded-for"]=ip),headers}getServiceRouteTable(serviceName){if(!this.serviceRoutesTable){this.serviceRoutesTable=new Map;for(let service of this.services||[]){if(!(0,import_build_utils9.isExperimentalServiceV2)(service))continue;let{routes,error:error2}=(0,import_routing_utils3.getTransformedRoutes)({routes:service.routes,rewrites:service.rewrites,redirects:service.redirects,headers:service.headers,cleanUrls:service.cleanUrls,trailingSlash:service.trailingSlash});error2?(output_manager_default.warn(`Invalid routes for service "${service.name}": ${error2.message}`),this.serviceRoutesTable.set(service.name,[])):this.serviceRoutesTable.set(service.name,routes||[])}}return this.serviceRoutesTable.get(serviceName)||[]}async delegateToService(req,res,requestId,matchedRoute,vercelConfig,requestTransforms,responseTransforms){let{debug}=output_manager_default,{service:serviceName,path:destPath}=matchedRoute.destination,origin=this.orchestrator?.getServiceOrigin(serviceName);if(!origin){output_manager_default.error(`Cannot route to service ${cmd(serviceName)}: it is not running.`),await this.sendError(req,res,requestId,"FUNCTION_INVOCATION_FAILED",502);return}let parsed=url3.parse(req.url||"/"),originalPathname=parsed.pathname||"/",lookupPath=originalPathname;if(typeof destPath=="string"&&matchedRoute.src){let keys=[],matcher=(0,import_pcre_to_regexp2.default)(`%${matchedRoute.src}%${this.isCaseSensitive()?"":"i"}`,keys),match=matcher.exec(originalPathname)||matcher.exec(originalPathname.substring(1));lookupPath=match?resolveRouteParameters(destPath,match,keys):destPath}let serviceRoutes=this.getServiceRouteTable(serviceName),proxyHeaders=this.getProxyHeaders(req,requestId,!1),requestTransformsToApply=[...requestTransforms??[]],responseTransformsToApply=responseTransforms,lookupUrl=`${lookupPath}${parsed.search||""}`,rewrittenUrl,externalDestUrl;if(serviceRoutes.length>0){let serviceResult=await devRouter(lookupUrl,req.method,serviceRoutes,this,vercelConfig);serviceResult.requestTransforms&&requestTransformsToApply.push(...serviceResult.requestTransforms),serviceResult.responseTransforms&&(responseTransformsToApply=serviceResult.responseTransforms);let location=serviceResult.headers?.location;if(location&&typeof serviceResult.status=="number"&&serviceResult.status>=300&&serviceResult.status<400){await this.sendRedirect(req,res,requestId,location,serviceResult.status,responseTransformsToApply);return}if(serviceResult.headers)for(let[name,value]of Object.entries(serviceResult.headers))name!=="location"&&res.setHeader(name,value);if(serviceResult.dest){let destParsed=url3.parse(serviceResult.dest),destQuery=parseQueryString(destParsed.search);Object.assign(destQuery,serviceResult.query),destParsed.search=formatQueryString(destQuery);let resolvedDest=url3.format(destParsed);serviceResult.isDestUrl?externalDestUrl=resolvedDest:resolvedDest!==lookupUrl&&(rewrittenUrl=resolvedDest)}}rewrittenUrl!==void 0&&(req.url=rewrittenUrl);for(let[name,value]of Object.entries(proxyHeaders))req.headers[name]=value;return this.prepareTransforms(req,requestTransformsToApply,responseTransformsToApply),this.setResponseHeaders(res,requestId),externalDestUrl?(debug(`Service "${serviceName}" rewrite to external URL: ${externalDestUrl}`),proxyPass(req,res,externalDestUrl,this,requestId)):(debug(`Delegating to service "${serviceName}": ${origin}${req.url}`),proxyPass(req,res,origin,this,requestId,!1))}async triggerBuild(match,requestPath,req,vercelConfig,previousBuildResult,filesChanged,filesRemoved){let functionBuild=this.canonicalizeFunctionBuild(match),cacheKey=functionBuild?null:requestPath,builds=this.inProgressBuilds.get(match)??new Map;if(functionBuild&&[...builds.keys()].some(key=>key!==null)){let pending=[...new Set(builds.values())],promise=pending.length===1?pending[0]:Promise.all(pending).then(()=>{});builds.clear(),builds.set(null,promise)}let buildKey=requestPath===null?match.entrypoint:`${match.entrypoint}-${requestPath}`,buildPromise=builds.get(cacheKey);if(buildPromise){let msg=`De-duping build "${buildKey}"`;req&&(msg+=` for "${req.method} ${req.url}"`),output_manager_default.debug(msg)}else{if(previousBuildResult)for(let[name]of Object.entries(previousBuildResult.output))output_manager_default.debug(`Removing asset "${name}"`),delete match.buildOutput[name];let msg=`Building asset "${buildKey}"`;req&&(msg+=` for "${req.method} ${req.url}"`),output_manager_default.debug(msg),buildPromise=executeBuild(vercelConfig,this,this.files,match,requestPath,!1,filesChanged,filesRemoved),builds.set(cacheKey,buildPromise),this.inProgressBuilds.set(match,builds)}try{await buildPromise,this.canonicalizeFunctionBuild(match)}finally{output_manager_default.debug(`Built asset ${buildKey}`),builds.get(cacheKey)===buildPromise&&builds.delete(cacheKey),builds.size===0&&this.inProgressBuilds.get(match)===builds&&this.inProgressBuilds.delete(match)}}async handleSchedulesProxyRequest(req,res){let pathname=(req.url||"/").split("?")[0];if(!pathname.startsWith(`${DEV_SCHEDULES_PROXY_PREFIX}/`))return!1;let prefix=`${DEV_SCHEDULES_PROXY_PREFIX}/${this.resourceProxyToken}`;return!this.schedulesOrigin||!pathname.startsWith(`${prefix}/`)?(res.writeHead(404),res.end("Not Found")):this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)?!isValidDevResourceHost(this.address.origin,req.headers.host)&&req.headers.host?.toLowerCase()!==this.address.host&&req.headers.host?.toLowerCase()!==`host.docker.internal${this.address.port?`:${this.address.port}`:""}`?(res.writeHead(403),res.end("Forbidden")):await this.handleSchedulesRoute(req,res,pathname.slice(prefix.length)):(res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized")),!0}renderDirectoryListing(_req,res,requestPath,requestId){if(this.projectSettings?.directoryListing===!1)return!1;let prefix=requestPath;prefix.length>0&&!prefix.endsWith("/")&&(prefix+="/");let dirs=new Set,files=Array.from(this.buildMatches.keys()).filter(p=>{let base=basename(p);if(base==="now.json"||base==="vercel.json"||base==="vercel.toml"||base===".nowignore"||base===".vercelignore"||!p.startsWith(prefix))return!1;let rel=relative2(prefix,p);if(rel.includes("/")){let dir=rel.split("/")[0];if(dirs.has(dir))return!1;dirs.add(dir)}return!0}).map(p=>{let base=basename(p),ext="",type="file",href,rel=relative2(prefix,p);return rel.includes("/")?(type="folder",base=rel.split("/")[0],href=`/${prefix}${base}/`):(ext=extname2(p).substring(1),href=`/${prefix}${base}`),{type,relative:href,ext,title:href,base}});if(files.length===0)return!1;let directory=`/${prefix}`,directoryHtml=(0,import_directory.default)({files,paths:[{name:directory,url:requestPath}],directory});return this.setResponseHeaders(res,requestId),res.setHeader("Content-Type","text/html; charset=utf-8"),res.setHeader("Content-Length",String(Buffer.byteLength(directoryHtml,"utf8"))),res.end(directoryHtml),!0}async hasFilesystem(dest,vercelConfig){return!!await findBuildMatch(this.buildMatches,this.files,dest,this,vercelConfig,!0)}isCaseSensitive(){return this.caseSensitive}runDevCommand(...args2){let start=this._runDevCommand(...args2);this.devCommandStarts.add(start);let clear=()=>{this.devCommandStarts.delete(start)};return start.then(clear,clear),start}async _runDevCommand(forceRestart=!1,{projectSettings,allEnv}={projectSettings:this.projectSettings,allEnv:this.envConfigs.allEnv},onReady=origin=>{this.devProcessOrigin=origin}){if(this.stopping||this.shouldUseServicesOrchestrator())return;let{cwd}=this,devCommand2=this.getDevCommand(projectSettings);if(devCommand2===this.currentDevCommand&&!forceRestart&&(!devCommand2||this.devProcess&&this.devProcessOrigin)||(this.currentDevCommand=devCommand2,this.devProcessOrigin=void 0,this.devProcess&&(this.devProcess.pid&&await treeKill(this.devProcess.pid),this.devProcess=void 0),this.devCommandEnv=void 0,this.stopping))return;if(!devCommand2){onReady(void 0);return}output_manager_default.log(`Running Dev Command ${import_chalk2.default.cyan.bold(`\u201C${devCommand2}\u201D`)}`);let port=await(0,import_get_port2.default)();if(this.stopping)return;let env=(0,import_build_utils9.cloneEnv)({FORCE_COLOR:process.stdout.isTTY?"1":"0",BROWSER:"none"},process.env,allEnv,this.getDevQueueEnv(),getDevSchedulesEnv(this.schedulesOrigin),{PORT:`${port}`,VERCEL_CLI_VERSION:pkg_default.version});Object.assign(env,this.getDevRuntimeCacheEnv(env));let nodeBinPath=(0,import_build_utils9.getNodeBinPaths)({base:this.repoRoot,start:cwd}).join(path4.delimiter);env.PATH=`${nodeBinPath}${path4.delimiter}${env.PATH}`;let command=replaceDevCommandPort(devCommand2,port);injectNextDevWebSocketShimIfNeeded(env,command,projectSettings),output_manager_default.debug(`Starting dev command with parameters: ${JSON.stringify({cwd,command,port})}`),output_manager_default.debug(`Spawning dev command: ${command}`);let proxyPort=new RegExp(port.toString(),"g"),p=(0,import_build_utils9.spawnCommand)(command,{stdio:["inherit","pipe","pipe"],cwd,env});if(this.devProcess=p,this.devCommandEnv={...allEnv},!p.stdout||!p.stderr)throw dev.DEV_INTERNAL_MISSING_CHILD_STDIO();p.stderr.pipe(process.stderr),p.stdout.setEncoding("utf8"),p.stdout.on("data",data=>{process.stdout.write(data.replace(proxyPort,this.address.port))});let devProcessExited=new Promise((_,reject)=>{p.on("error",err=>{output_manager_default.debug(`Dev command errored: ${err}`),reject(err)}),p.on("exit",(code,signal)=>{output_manager_default.debug(`Dev command exited with "${signal||code}"`),reject(new DevCommandExitError(`Dev command \u201C${devCommand2}\u201D exited with code ${signal||code}`,code??1))})});p.on("close",(code,signal)=>{output_manager_default.debug(`Dev command closed with "${signal||code}"`),this.devProcess===p&&(this.devProcessOrigin=void 0)});let devProcessHost=await Promise.race([checkForPort(port,DEV_SERVER_PORT_BIND_TIMEOUT),devProcessExited]);this.stopping||onReady(`http://${devProcessHost}:${port}`)}};function isServiceDestination(route){return!!route&&!(0,import_routing_utils3.isHandler)(route)&&typeof route.destination=="object"&&route.destination!==null&&"service"in route.destination&&typeof route.destination.service=="string"}function proxyPass(req,res,dest,devServer,requestId,ignorePath=!0){devServer.proxy.web(req,res,{target:dest,ignorePath},error2=>{devServer.clearResponseTransforms(req),output_manager_default.debug(`Failed to complete request to ${req.url}: ${error2}`),res.headersSent||devServer.sendError(req,res,requestId,"FUNCTION_INVOCATION_FAILED")})}function serveStaticFile(req,res,cwd,opts){return(0,import_serve_handler.default)(req,res,{public:cwd,cleanUrls:!1,etag:!0,...opts})}function close(server){return new Promise((resolve3,reject)=>{server.close(err=>{err&&(!(0,import_error_utils.isErrnoException)(err)||err.code!=="ERR_SERVER_NOT_RUNNING")?reject(err):resolve3()})})}function generateRequestId(podId,isInvoke=!1){return`dev1::${isInvoke?"dev1::":""}${[podId,Date.now(),randomBytes2(6).toString("hex")].join("-")}`}function hasProp(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}async function findBuildMatch(matches,files,requestPath,devServer,vercelConfig,isFilesystem=!1){requestPath=requestPath.replace(/^\//,"");let bestIndexMatch;for(let match of matches.values())if(await shouldServe(match,files,requestPath,devServer,vercelConfig,isFilesystem,!!bestIndexMatch))if(isIndex(match.src)){if(extname2(match.src)===".html")return match;bestIndexMatch=match}else return match;return bestIndexMatch||null}async function shouldServe(match,files,requestPath,devServer,vercelConfig,isFilesystem=!1,hasMatched=!1){let{src,config,builderWithPkg:{builder}}=match;if(config?.middleware===!0||config?.scheduleFunction)return!1;let cleanSrc=src.endsWith(".html")?src.slice(0,-5):src,trimmedPath=requestPath.endsWith("/")?requestPath.slice(0,-1):requestPath;if(vercelConfig.cleanUrls&&vercelConfig.trailingSlash&&cleanSrc===trimmedPath)return!0;if(vercelConfig.cleanUrls&&!vercelConfig.trailingSlash&&cleanSrc===requestPath)return!0;if(!vercelConfig.cleanUrls&&vercelConfig.trailingSlash&&src===trimmedPath)return!0;if(typeof builder.shouldServe=="function"){if(await builder.shouldServe({entrypoint:src,files,config:config||{},requestPath,workPath:devServer.cwd,hasMatched}))return!0}else{if(findAsset(match,requestPath,vercelConfig))return!0;if(!isFilesystem&&await findMatchingRoute(match,requestPath,devServer,vercelConfig))return!0}return!1}async function findMatchingRoute(match,requestPath,devServer,vercelConfig){let reqUrl=`/${requestPath}`;for(let buildResult of match.buildResults.values()){if(!Array.isArray(buildResult.routes))continue;let route=await devRouter(reqUrl,void 0,buildResult.routes,devServer,vercelConfig);if(route.found)return route}}function findAsset(match,requestPath,vercelConfig){if(!match.buildOutput)return;let assetKey=requestPath.replace(/\/$/,""),asset=match.buildOutput[requestPath];if(vercelConfig.trailingSlash&&requestPath.endsWith("/")&&(asset=match.buildOutput[requestPath.slice(0,-1)]),!asset){for(let[name,a]of Object.entries(match.buildOutput))if(isIndex(name)&&dirnameWithoutDot(name)===assetKey){asset=a,assetKey=name;break}}if(asset)return{asset,assetKey}}function dirnameWithoutDot(path6){let dir=dirname3(path6);return dir==="."&&(dir=""),dir}function isIndex(path6){let ext=extname2(path6);return basename(path6,ext)==="index"}function minimatches(files,pattern){return files.some(file=>file===pattern||(0,import_minimatch3.default)(file,pattern,{dot:!0}))}function fileChanged(name,changed,removed){changed.add(name),removed.delete(name)}function fileRemoved(name,files,changed,removed){delete files[name],changed.delete(name),removed.add(name)}function needsBlockingBuild(buildMatch){let{builder}=buildMatch.builderWithPkg;return typeof builder.shouldServe!="function"}function hasNewRoutingProperties(vercelConfig){return typeof vercelConfig.cleanUrls!==void 0||typeof vercelConfig.headers!==void 0||typeof vercelConfig.redirects!==void 0||typeof vercelConfig.rewrites!==void 0||typeof vercelConfig.trailingSlash!==void 0}function buildMatchEquals(a,b){return!(!a||!b||a.src!==b.src||a.use!==b.use||!(0,import_fast_deep_equal.default)(a.config||{},b.config||{}))}var import_ms7=__toESM(require_ms(),1);import{setTimeout as setTimeout2}from"node:timers/promises";import{decodeJwt}from"jose";import{performance}from"perf_hooks";var REFRESH_BEFORE_EXPIRY_MILLIS=getMs((0,import_ms7.default)("15m"),process.env.REFRESH_VERCEL_OIDC_TOKEN_BEFORE_EXPIRY_MILLIS),THROTTLE_MILLIS=getMs((0,import_ms7.default)("1m"),process.env.REFRESH_VERCEL_OIDC_TOKEN_THROTTLE_MILLIS);function getMs(defaultValue,overrideValue){if(overrideValue){let result=(0,import_ms7.default)(overrideValue);if(Number.isFinite(result)&&result>0)return result}return defaultValue}async function*refreshOidcToken(signal,client,projectId,envValues,source,throttleMillis){throttleMillis??=THROTTLE_MILLIS;let lastPulledEnvAt=clock(),refreshCount=0;for(;!signal.aborted;){let oidcToken=envValues[VERCEL_OIDC_TOKEN];if(!oidcToken){output_manager_default.debug(`${VERCEL_OIDC_TOKEN} is absent; disabling refreshes`);return}let now=clock(),expiresAfterMillis;try{let{exp}=decodeJwt(oidcToken);expiresAfterMillis=exp!==void 0?exp*1e3-now:void 0}catch{}if(expiresAfterMillis===void 0||!Number.isFinite(expiresAfterMillis)){output_manager_default.debug(`${VERCEL_OIDC_TOKEN} is invalid; disabling refreshes`);return}refreshCount++>0&&expiresAfterMillis>0&&(yield oidcToken);let refreshAfterMillis=Math.max(0,expiresAfterMillis-REFRESH_BEFORE_EXPIRY_MILLIS);now+refreshAfterMillis-lastPulledEnvAt<throttleMillis&&(refreshAfterMillis=throttleMillis);let expiresAfterSecs=Math.abs(Math.round(millisToSecs(expiresAfterMillis))),refreshAfterSecs=Math.round(millisToSecs(refreshAfterMillis));expiresAfterMillis<0?output_manager_default.debug(`${VERCEL_OIDC_TOKEN} expired ${expiresAfterSecs}s ago; refreshing in ${refreshAfterSecs}s`):output_manager_default.debug(`${VERCEL_OIDC_TOKEN} expires in ${expiresAfterSecs}s; refreshing in ${refreshAfterSecs}s`),await setTimeout2(refreshAfterMillis,void 0,{signal});let envValuesOrNull=await pullEnvValuesUntilSuccessful(signal,client,projectId,source,throttleMillis);if(!envValuesOrNull)return;envValues=envValuesOrNull,lastPulledEnvAt=clock()}}async function pullEnvValuesUntilSuccessful(signal,client,projectId,source,millis){for(;!signal.aborted;)try{return(await pullEnvRecords(client,projectId,source)).env}catch{output_manager_default.debug(`Failed to pull environment; trying again in ${Math.round(millisToSecs(millis))}s`),await setTimeout2(millis,void 0,{signal})}return null}function clock(){return performance.timeOrigin+performance.now()}function millisToSecs(millis){return millis/1e3}import{join as join5}from"path";import{mkdir,open,unlink,readFile as readFile2}from"fs/promises";import{unlinkSync as unlinkSync2,constants}from"fs";var DEV_LOCK_FILE="dev.lock";function isProcessRunning(pid){try{return process.kill(pid,0),!0}catch{return!1}}async function tryCreateLockFile(lockPath,content){try{let fd=await open(lockPath,constants.O_CREAT|constants.O_EXCL|constants.O_WRONLY);return await fd.writeFile(content,"utf8"),await fd.close(),!0}catch(err){if(err.code==="EEXIST")return!1;throw err}}async function tryReadLockFile(lockPath){try{let content=await readFile2(lockPath,"utf8");return JSON.parse(content)}catch{return null}}async function acquireDevLock(projectRoot,port){let vercelDir=join5(projectRoot,VERCEL_DIR),lockPath=join5(vercelDir,DEV_LOCK_FILE);await mkdir(vercelDir,{recursive:!0});let lockData={pid:process.pid,port,startedAt:Date.now(),cwd:projectRoot},lockContent=JSON.stringify(lockData);try{if(await tryCreateLockFile(lockPath,lockContent))return{acquired:!0}}catch(err){output_manager_default.debug(`Failed to create lock file: ${err}`)}let existingLock=await tryReadLockFile(lockPath);if(existingLock){if(isProcessRunning(existingLock.pid))return{acquired:!1,existingLock};output_manager_default.debug(`Removing stale lock from PID ${existingLock.pid}`);try{await unlink(lockPath)}catch(err){output_manager_default.debug(`Failed to remove stale lock file: ${err}`)}try{if(await tryCreateLockFile(lockPath,lockContent))return{acquired:!0}}catch(err){output_manager_default.debug(`Failed to create lock after removing stale: ${err}`)}let newLock=await tryReadLockFile(lockPath);if(newLock)return{acquired:!1,existingLock:newLock}}else output_manager_default.debug("Lock file exists but cannot be read");return{acquired:!1,existingLock:null,reason:`The lock file at \`${lockPath}\` could not be read. If no other \`vercel dev\` is running, remove it and retry.`}}function releaseDevLock(projectRoot){let lockPath=join5(projectRoot,VERCEL_DIR,DEV_LOCK_FILE);try{unlinkSync2(lockPath)}catch(err){output_manager_default.debug(`Failed to release lock: ${err}`)}}function parseResourcePort(value,flag){if(value===void 0)return;if(!/^\d+$/.test(value))throw new Error(`${flag} must be an integer between 0 and 65535`);let port=Number(value);if(!Number.isSafeInteger(port)||port>65535)throw new Error(`${flag} must be an integer between 0 and 65535`);return port}async function dev2(client,opts,args2,telemetry,localConfig){let[dir="."]=args2,cwd=resolve2(dir),localConfigCwd=cwd,listen2=parseListen(opts["--listen"]||"3000"),queuePort=parseResourcePort(opts["--queue-port"],"--queue-port"),runtimeCachePort=parseResourcePort(opts["--runtime-cache-port"],"--runtime-cache-port"),schedulesPort=parseResourcePort(opts["--schedules-port"],"--schedules-port"),resourcePorts=[["--queue-port",queuePort],["--runtime-cache-port",runtimeCachePort],["--schedules-port",schedulesPort]];for(let[index,[flag,port]]of resourcePorts.entries()){let duplicate=resourcePorts.slice(0,index).find(([,otherPort])=>port!==void 0&&port!==0&&port===otherPort);if(duplicate)throw new Error(`${duplicate[0]} and ${flag} must use different ports`)}cwd=await resolveProjectCwd(cwd);let projectNameOrId=opts["--project"],reportError=createErrorReporter(code=>telemetry.trackError(code)),link=await getLinkedProject(client,{cwd,projectName:projectNameOrId,projectNameIsExplicit:!!projectNameOrId,scopeIsExplicit:detectExplicitScope(client)});if(link.status==="not_linked"&&!process.env.__VERCEL_SKIP_DEV_CMD)if(opts["--local"])output_manager_default.warn(`Running dev server in local mode without a project setup:
68
+ `),res.end(body)}getRequestIp(req){return req.connection.remoteAddress||"127.0.0.1"}setResponseHeaders(res,requestId,headers={}){let allHeaders={"cache-control":"public, max-age=0, must-revalidate",...headers,server:"Vercel","x-vercel-id":requestId,"x-vercel-cache":"MISS"};for(let[name,value]of Object.entries(allHeaders))res.setHeader(name,value)}prepareTransforms(req,requestTransforms,responseTransforms){requestTransforms&&requestTransforms.length>0&&applyRequestTransforms(req,requestTransforms),responseTransforms&&hasResponseTransforms(responseTransforms)&&this.responseTransformsByReq.set(req,responseTransforms)}clearResponseTransforms(req){this.responseTransformsByReq.delete(req)}getProxyHeaders(req,requestId,xfwd){let ip=this.getRequestIp(req),{host}=req.headers,headers={connection:"close","x-real-ip":ip,"x-vercel-deployment-url":host,"x-vercel-forwarded-for":ip,"x-vercel-id":requestId};return xfwd&&(headers["x-forwarded-host"]=host,headers["x-forwarded-proto"]="http",headers["x-forwarded-for"]=ip),headers}getServiceRouteTable(serviceName){if(!this.serviceRoutesTable){this.serviceRoutesTable=new Map;for(let service of this.services||[]){if(!(0,import_build_utils9.isExperimentalServiceV2)(service))continue;let{routes,error:error2}=(0,import_routing_utils3.getTransformedRoutes)({routes:service.routes,rewrites:service.rewrites,redirects:service.redirects,headers:service.headers,cleanUrls:service.cleanUrls,trailingSlash:service.trailingSlash});error2?(output_manager_default.warn(`Invalid routes for service "${service.name}": ${error2.message}`),this.serviceRoutesTable.set(service.name,[])):this.serviceRoutesTable.set(service.name,routes||[])}}return this.serviceRoutesTable.get(serviceName)||[]}async delegateToService(req,res,requestId,matchedRoute,vercelConfig,requestTransforms,responseTransforms){let{debug}=output_manager_default,{service:serviceName,path:destPath}=matchedRoute.destination,origin=this.orchestrator?.getServiceOrigin(serviceName);if(!origin){output_manager_default.error(`Cannot route to service ${cmd(serviceName)}: it is not running.`),await this.sendError(req,res,requestId,"FUNCTION_INVOCATION_FAILED",502);return}let parsed=url3.parse(req.url||"/"),originalPathname=parsed.pathname||"/",lookupPath=originalPathname;if(typeof destPath=="string"&&matchedRoute.src){let keys=[],matcher=(0,import_pcre_to_regexp2.default)(`%${matchedRoute.src}%${this.isCaseSensitive()?"":"i"}`,keys),match=matcher.exec(originalPathname)||matcher.exec(originalPathname.substring(1));lookupPath=match?resolveRouteParameters(destPath,match,keys):destPath}let serviceRoutes=this.getServiceRouteTable(serviceName),proxyHeaders=this.getProxyHeaders(req,requestId,!1),requestTransformsToApply=[...requestTransforms??[]],responseTransformsToApply=responseTransforms,lookupUrl=`${lookupPath}${parsed.search||""}`,rewrittenUrl,externalDestUrl;if(serviceRoutes.length>0){let serviceResult=await devRouter(lookupUrl,req.method,serviceRoutes,this,vercelConfig);serviceResult.requestTransforms&&requestTransformsToApply.push(...serviceResult.requestTransforms),serviceResult.responseTransforms&&(responseTransformsToApply=serviceResult.responseTransforms);let location=serviceResult.headers?.location;if(location&&typeof serviceResult.status=="number"&&serviceResult.status>=300&&serviceResult.status<400){await this.sendRedirect(req,res,requestId,location,serviceResult.status,responseTransformsToApply);return}if(serviceResult.headers)for(let[name,value]of Object.entries(serviceResult.headers))name!=="location"&&res.setHeader(name,value);if(serviceResult.dest){let destParsed=url3.parse(serviceResult.dest),destQuery=parseQueryString(destParsed.search);Object.assign(destQuery,serviceResult.query),destParsed.search=formatQueryString(destQuery);let resolvedDest=url3.format(destParsed);serviceResult.isDestUrl?externalDestUrl=resolvedDest:resolvedDest!==lookupUrl&&(rewrittenUrl=resolvedDest)}}rewrittenUrl!==void 0&&(req.url=rewrittenUrl);for(let[name,value]of Object.entries(proxyHeaders))req.headers[name]=value;return this.prepareTransforms(req,requestTransformsToApply,responseTransformsToApply),this.setResponseHeaders(res,requestId),externalDestUrl?(debug(`Service "${serviceName}" rewrite to external URL: ${externalDestUrl}`),proxyPass(req,res,externalDestUrl,this,requestId)):(debug(`Delegating to service "${serviceName}": ${origin}${req.url}`),proxyPass(req,res,origin,this,requestId,!1))}async triggerBuild(match,requestPath,req,vercelConfig,previousBuildResult,filesChanged,filesRemoved){let functionBuild=this.canonicalizeFunctionBuild(match),cacheKey=functionBuild?null:requestPath,builds=this.inProgressBuilds.get(match)??new Map;if(functionBuild&&[...builds.keys()].some(key=>key!==null)){let pending=[...new Set(builds.values())],promise=pending.length===1?pending[0]:Promise.all(pending).then(()=>{});builds.clear(),builds.set(null,promise)}let buildKey=requestPath===null?match.entrypoint:`${match.entrypoint}-${requestPath}`,buildPromise=builds.get(cacheKey);if(buildPromise){let msg=`De-duping build "${buildKey}"`;req&&(msg+=` for "${req.method} ${req.url}"`),output_manager_default.debug(msg)}else{if(previousBuildResult)for(let[name]of Object.entries(previousBuildResult.output))output_manager_default.debug(`Removing asset "${name}"`),delete match.buildOutput[name];let msg=`Building asset "${buildKey}"`;req&&(msg+=` for "${req.method} ${req.url}"`),output_manager_default.debug(msg),buildPromise=executeBuild(vercelConfig,this,this.files,match,requestPath,!1,filesChanged,filesRemoved),builds.set(cacheKey,buildPromise),this.inProgressBuilds.set(match,builds)}try{await buildPromise,this.canonicalizeFunctionBuild(match)}finally{output_manager_default.debug(`Built asset ${buildKey}`),builds.get(cacheKey)===buildPromise&&builds.delete(cacheKey),builds.size===0&&this.inProgressBuilds.get(match)===builds&&this.inProgressBuilds.delete(match)}}async handleSchedulesProxyRequest(req,res){let pathname=(req.url||"/").split("?")[0];if(!pathname.startsWith(`${DEV_SCHEDULES_PROXY_PREFIX}/`))return!1;this.schedulesSession&&res.setHeader(LOCAL_SCHEDULES_SESSION_HEADER,this.schedulesSession.session.id);let prefix=`${DEV_SCHEDULES_PROXY_PREFIX}/${this.resourceProxyToken}`;return!this.schedulesOrigin||!pathname.startsWith(`${prefix}/`)?(res.writeHead(404),res.end("Not Found")):this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)?!isValidDevResourceHost(this.address.origin,req.headers.host)&&req.headers.host?.toLowerCase()!==this.address.host&&req.headers.host?.toLowerCase()!==`host.docker.internal${this.address.port?`:${this.address.port}`:""}`?(res.writeHead(403),res.end("Forbidden")):await this.handleSchedulesRoute(req,res,pathname.slice(prefix.length)):(res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized")),!0}renderDirectoryListing(_req,res,requestPath,requestId){if(this.projectSettings?.directoryListing===!1)return!1;let prefix=requestPath;prefix.length>0&&!prefix.endsWith("/")&&(prefix+="/");let dirs=new Set,files=Array.from(this.buildMatches.keys()).filter(p=>{let base=basename(p);if(base==="now.json"||base==="vercel.json"||base==="vercel.toml"||base===".nowignore"||base===".vercelignore"||!p.startsWith(prefix))return!1;let rel=relative2(prefix,p);if(rel.includes("/")){let dir=rel.split("/")[0];if(dirs.has(dir))return!1;dirs.add(dir)}return!0}).map(p=>{let base=basename(p),ext="",type="file",href,rel=relative2(prefix,p);return rel.includes("/")?(type="folder",base=rel.split("/")[0],href=`/${prefix}${base}/`):(ext=extname2(p).substring(1),href=`/${prefix}${base}`),{type,relative:href,ext,title:href,base}});if(files.length===0)return!1;let directory=`/${prefix}`,directoryHtml=(0,import_directory.default)({files,paths:[{name:directory,url:requestPath}],directory});return this.setResponseHeaders(res,requestId),res.setHeader("Content-Type","text/html; charset=utf-8"),res.setHeader("Content-Length",String(Buffer.byteLength(directoryHtml,"utf8"))),res.end(directoryHtml),!0}async hasFilesystem(dest,vercelConfig){return!!await findBuildMatch(this.buildMatches,this.files,dest,this,vercelConfig,!0)}isCaseSensitive(){return this.caseSensitive}runDevCommand(...args2){let start=this._runDevCommand(...args2);this.devCommandStarts.add(start);let clear=()=>{this.devCommandStarts.delete(start)};return start.then(clear,clear),start}async _runDevCommand(forceRestart=!1,{projectSettings,allEnv}={projectSettings:this.projectSettings,allEnv:this.envConfigs.allEnv},onReady=origin=>{this.devProcessOrigin=origin}){if(this.stopping||this.shouldUseServicesOrchestrator())return;let{cwd}=this,devCommand2=this.getDevCommand(projectSettings);if(devCommand2===this.currentDevCommand&&!forceRestart&&(!devCommand2||this.devProcess&&this.devProcessOrigin)||(this.currentDevCommand=devCommand2,this.devProcessOrigin=void 0,this.devProcess&&(this.devProcess.pid&&await treeKill(this.devProcess.pid),this.devProcess=void 0),this.devCommandEnv=void 0,this.stopping))return;if(!devCommand2){onReady(void 0);return}output_manager_default.log(`Running Dev Command ${import_chalk2.default.cyan.bold(`\u201C${devCommand2}\u201D`)}`);let port=await(0,import_get_port2.default)();if(this.stopping)return;let env=(0,import_build_utils9.cloneEnv)({FORCE_COLOR:process.stdout.isTTY?"1":"0",BROWSER:"none"},process.env,allEnv,this.getDevQueueEnv(),getDevSchedulesEnv(this.schedulesOrigin),{PORT:`${port}`,VERCEL_CLI_VERSION:pkg_default.version});Object.assign(env,this.getDevRuntimeCacheEnv(env));let nodeBinPath=(0,import_build_utils9.getNodeBinPaths)({base:this.repoRoot,start:cwd}).join(path4.delimiter);env.PATH=`${nodeBinPath}${path4.delimiter}${env.PATH}`;let command=replaceDevCommandPort(devCommand2,port);injectNextDevWebSocketShimIfNeeded(env,command,projectSettings),output_manager_default.debug(`Starting dev command with parameters: ${JSON.stringify({cwd,command,port})}`),output_manager_default.debug(`Spawning dev command: ${command}`);let proxyPort=new RegExp(port.toString(),"g"),p=(0,import_build_utils9.spawnCommand)(command,{stdio:["inherit","pipe","pipe"],cwd,env});if(this.devProcess=p,this.devCommandEnv={...allEnv},!p.stdout||!p.stderr)throw dev.DEV_INTERNAL_MISSING_CHILD_STDIO();p.stderr.pipe(process.stderr),p.stdout.setEncoding("utf8"),p.stdout.on("data",data=>{process.stdout.write(data.replace(proxyPort,this.address.port))});let devProcessExited=new Promise((_,reject)=>{p.on("error",err=>{output_manager_default.debug(`Dev command errored: ${err}`),reject(err)}),p.on("exit",(code,signal)=>{output_manager_default.debug(`Dev command exited with "${signal||code}"`),reject(new DevCommandExitError(`Dev command \u201C${devCommand2}\u201D exited with code ${signal||code}`,code??1))})});p.on("close",(code,signal)=>{output_manager_default.debug(`Dev command closed with "${signal||code}"`),this.devProcess===p&&(this.devProcessOrigin=void 0)});let devProcessHost=await Promise.race([checkForPort(port,DEV_SERVER_PORT_BIND_TIMEOUT),devProcessExited]);this.stopping||onReady(`http://${devProcessHost}:${port}`)}};function isServiceDestination(route){return!!route&&!(0,import_routing_utils3.isHandler)(route)&&typeof route.destination=="object"&&route.destination!==null&&"service"in route.destination&&typeof route.destination.service=="string"}function proxyPass(req,res,dest,devServer,requestId,ignorePath=!0){devServer.proxy.web(req,res,{target:dest,ignorePath},error2=>{devServer.clearResponseTransforms(req),output_manager_default.debug(`Failed to complete request to ${req.url}: ${error2}`),res.headersSent||devServer.sendError(req,res,requestId,"FUNCTION_INVOCATION_FAILED")})}function serveStaticFile(req,res,cwd,opts){return(0,import_serve_handler.default)(req,res,{public:cwd,cleanUrls:!1,etag:!0,...opts})}function close(server){return new Promise((resolve3,reject)=>{server.close(err=>{err&&(!(0,import_error_utils.isErrnoException)(err)||err.code!=="ERR_SERVER_NOT_RUNNING")?reject(err):resolve3()})})}function generateRequestId(podId,isInvoke=!1){return`dev1::${isInvoke?"dev1::":""}${[podId,Date.now(),randomBytes2(6).toString("hex")].join("-")}`}function hasProp(obj,prop){return Object.prototype.hasOwnProperty.call(obj,prop)}async function findBuildMatch(matches,files,requestPath,devServer,vercelConfig,isFilesystem=!1){requestPath=requestPath.replace(/^\//,"");let bestIndexMatch;for(let match of matches.values())if(await shouldServe(match,files,requestPath,devServer,vercelConfig,isFilesystem,!!bestIndexMatch))if(isIndex(match.src)){if(extname2(match.src)===".html")return match;bestIndexMatch=match}else return match;return bestIndexMatch||null}async function shouldServe(match,files,requestPath,devServer,vercelConfig,isFilesystem=!1,hasMatched=!1){let{src,config,builderWithPkg:{builder}}=match;if(config?.middleware===!0||config?.scheduleFunction)return!1;let cleanSrc=src.endsWith(".html")?src.slice(0,-5):src,trimmedPath=requestPath.endsWith("/")?requestPath.slice(0,-1):requestPath;if(vercelConfig.cleanUrls&&vercelConfig.trailingSlash&&cleanSrc===trimmedPath)return!0;if(vercelConfig.cleanUrls&&!vercelConfig.trailingSlash&&cleanSrc===requestPath)return!0;if(!vercelConfig.cleanUrls&&vercelConfig.trailingSlash&&src===trimmedPath)return!0;if(typeof builder.shouldServe=="function"){if(await builder.shouldServe({entrypoint:src,files,config:config||{},requestPath,workPath:devServer.cwd,hasMatched}))return!0}else{if(findAsset(match,requestPath,vercelConfig))return!0;if(!isFilesystem&&await findMatchingRoute(match,requestPath,devServer,vercelConfig))return!0}return!1}async function findMatchingRoute(match,requestPath,devServer,vercelConfig){let reqUrl=`/${requestPath}`;for(let buildResult of match.buildResults.values()){if(!Array.isArray(buildResult.routes))continue;let route=await devRouter(reqUrl,void 0,buildResult.routes,devServer,vercelConfig);if(route.found)return route}}function findAsset(match,requestPath,vercelConfig){if(!match.buildOutput)return;let assetKey=requestPath.replace(/\/$/,""),asset=match.buildOutput[requestPath];if(vercelConfig.trailingSlash&&requestPath.endsWith("/")&&(asset=match.buildOutput[requestPath.slice(0,-1)]),!asset){for(let[name,a]of Object.entries(match.buildOutput))if(isIndex(name)&&dirnameWithoutDot(name)===assetKey){asset=a,assetKey=name;break}}if(asset)return{asset,assetKey}}function dirnameWithoutDot(path6){let dir=dirname3(path6);return dir==="."&&(dir=""),dir}function isIndex(path6){let ext=extname2(path6);return basename(path6,ext)==="index"}function minimatches(files,pattern){return files.some(file=>file===pattern||(0,import_minimatch3.default)(file,pattern,{dot:!0}))}function fileChanged(name,changed,removed){changed.add(name),removed.delete(name)}function fileRemoved(name,files,changed,removed){delete files[name],changed.delete(name),removed.add(name)}function needsBlockingBuild(buildMatch){let{builder}=buildMatch.builderWithPkg;return typeof builder.shouldServe!="function"}function hasNewRoutingProperties(vercelConfig){return typeof vercelConfig.cleanUrls!==void 0||typeof vercelConfig.headers!==void 0||typeof vercelConfig.redirects!==void 0||typeof vercelConfig.rewrites!==void 0||typeof vercelConfig.trailingSlash!==void 0}function buildMatchEquals(a,b){return!(!a||!b||a.src!==b.src||a.use!==b.use||!(0,import_fast_deep_equal.default)(a.config||{},b.config||{}))}var import_ms7=__toESM(require_ms(),1);import{setTimeout as setTimeout2}from"node:timers/promises";import{decodeJwt}from"jose";import{performance}from"perf_hooks";var REFRESH_BEFORE_EXPIRY_MILLIS=getMs((0,import_ms7.default)("15m"),process.env.REFRESH_VERCEL_OIDC_TOKEN_BEFORE_EXPIRY_MILLIS),THROTTLE_MILLIS=getMs((0,import_ms7.default)("1m"),process.env.REFRESH_VERCEL_OIDC_TOKEN_THROTTLE_MILLIS);function getMs(defaultValue,overrideValue){if(overrideValue){let result=(0,import_ms7.default)(overrideValue);if(Number.isFinite(result)&&result>0)return result}return defaultValue}async function*refreshOidcToken(signal,client,projectId,envValues,source,throttleMillis){throttleMillis??=THROTTLE_MILLIS;let lastPulledEnvAt=clock(),refreshCount=0;for(;!signal.aborted;){let oidcToken=envValues[VERCEL_OIDC_TOKEN];if(!oidcToken){output_manager_default.debug(`${VERCEL_OIDC_TOKEN} is absent; disabling refreshes`);return}let now=clock(),expiresAfterMillis;try{let{exp}=decodeJwt(oidcToken);expiresAfterMillis=exp!==void 0?exp*1e3-now:void 0}catch{}if(expiresAfterMillis===void 0||!Number.isFinite(expiresAfterMillis)){output_manager_default.debug(`${VERCEL_OIDC_TOKEN} is invalid; disabling refreshes`);return}refreshCount++>0&&expiresAfterMillis>0&&(yield oidcToken);let refreshAfterMillis=Math.max(0,expiresAfterMillis-REFRESH_BEFORE_EXPIRY_MILLIS);now+refreshAfterMillis-lastPulledEnvAt<throttleMillis&&(refreshAfterMillis=throttleMillis);let expiresAfterSecs=Math.abs(Math.round(millisToSecs(expiresAfterMillis))),refreshAfterSecs=Math.round(millisToSecs(refreshAfterMillis));expiresAfterMillis<0?output_manager_default.debug(`${VERCEL_OIDC_TOKEN} expired ${expiresAfterSecs}s ago; refreshing in ${refreshAfterSecs}s`):output_manager_default.debug(`${VERCEL_OIDC_TOKEN} expires in ${expiresAfterSecs}s; refreshing in ${refreshAfterSecs}s`),await setTimeout2(refreshAfterMillis,void 0,{signal});let envValuesOrNull=await pullEnvValuesUntilSuccessful(signal,client,projectId,source,throttleMillis);if(!envValuesOrNull)return;envValues=envValuesOrNull,lastPulledEnvAt=clock()}}async function pullEnvValuesUntilSuccessful(signal,client,projectId,source,millis){for(;!signal.aborted;)try{return(await pullEnvRecords(client,projectId,source)).env}catch{output_manager_default.debug(`Failed to pull environment; trying again in ${Math.round(millisToSecs(millis))}s`),await setTimeout2(millis,void 0,{signal})}return null}function clock(){return performance.timeOrigin+performance.now()}function millisToSecs(millis){return millis/1e3}import{join as join5}from"path";import{mkdir,open,unlink,readFile as readFile2}from"fs/promises";import{unlinkSync as unlinkSync2,constants}from"fs";var DEV_LOCK_FILE="dev.lock";function isProcessRunning(pid){try{return process.kill(pid,0),!0}catch{return!1}}async function tryCreateLockFile(lockPath,content){try{let fd=await open(lockPath,constants.O_CREAT|constants.O_EXCL|constants.O_WRONLY);return await fd.writeFile(content,"utf8"),await fd.close(),!0}catch(err){if(err.code==="EEXIST")return!1;throw err}}async function tryReadLockFile(lockPath){try{let content=await readFile2(lockPath,"utf8");return JSON.parse(content)}catch{return null}}async function acquireDevLock(projectRoot,port){let vercelDir=join5(projectRoot,VERCEL_DIR),lockPath=join5(vercelDir,DEV_LOCK_FILE);await mkdir(vercelDir,{recursive:!0});let lockData={pid:process.pid,port,startedAt:Date.now(),cwd:projectRoot},lockContent=JSON.stringify(lockData);try{if(await tryCreateLockFile(lockPath,lockContent))return{acquired:!0}}catch(err){output_manager_default.debug(`Failed to create lock file: ${err}`)}let existingLock=await tryReadLockFile(lockPath);if(existingLock){if(isProcessRunning(existingLock.pid))return{acquired:!1,existingLock};output_manager_default.debug(`Removing stale lock from PID ${existingLock.pid}`);try{await unlink(lockPath)}catch(err){output_manager_default.debug(`Failed to remove stale lock file: ${err}`)}try{if(await tryCreateLockFile(lockPath,lockContent))return{acquired:!0}}catch(err){output_manager_default.debug(`Failed to create lock after removing stale: ${err}`)}let newLock=await tryReadLockFile(lockPath);if(newLock)return{acquired:!1,existingLock:newLock}}else output_manager_default.debug("Lock file exists but cannot be read");return{acquired:!1,existingLock:null,reason:`The lock file at \`${lockPath}\` could not be read. If no other \`vercel dev\` is running, remove it and retry.`}}function releaseDevLock(projectRoot){let lockPath=join5(projectRoot,VERCEL_DIR,DEV_LOCK_FILE);try{unlinkSync2(lockPath)}catch(err){output_manager_default.debug(`Failed to release lock: ${err}`)}}function parseResourcePort(value,flag){if(value===void 0)return;if(!/^\d+$/.test(value))throw new Error(`${flag} must be an integer between 0 and 65535`);let port=Number(value);if(!Number.isSafeInteger(port)||port>65535)throw new Error(`${flag} must be an integer between 0 and 65535`);return port}async function dev2(client,opts,args2,telemetry,localConfig){let[dir="."]=args2,cwd=resolve2(dir),localConfigCwd=cwd,listen2=parseListen(opts["--listen"]||"3000"),queuePort=parseResourcePort(opts["--queue-port"],"--queue-port"),runtimeCachePort=parseResourcePort(opts["--runtime-cache-port"],"--runtime-cache-port"),schedulesPort=parseResourcePort(opts["--schedules-port"],"--schedules-port"),resourcePorts=[["--queue-port",queuePort],["--runtime-cache-port",runtimeCachePort],["--schedules-port",schedulesPort]];for(let[index,[flag,port]]of resourcePorts.entries()){let duplicate=resourcePorts.slice(0,index).find(([,otherPort])=>port!==void 0&&port!==0&&port===otherPort);if(duplicate)throw new Error(`${duplicate[0]} and ${flag} must use different ports`)}cwd=await resolveProjectCwd(cwd);let projectNameOrId=opts["--project"],reportError=createErrorReporter(code=>telemetry.trackError(code)),link=await getLinkedProject(client,{cwd,projectName:projectNameOrId,projectNameIsExplicit:!!projectNameOrId,scopeIsExplicit:detectExplicitScope(client)});if(link.status==="not_linked"&&!process.env.__VERCEL_SKIP_DEV_CMD)if(opts["--local"])output_manager_default.warn(`Running dev server in local mode without a project setup:
69
69
  - Environment variables will not be pulled from Vercel
70
70
  - Project settings are defined by local configuration
71
71