@vercel/cli-support 68.3.0-snapshot-24d117b8c08a → 68.3.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 (157) hide show
  1. package/dist/chunks/{add-UC3PDROQ.js → add-6QNDJVXV.js} +1 -1
  2. package/dist/chunks/{add-K63YQ4KL.js → add-LVSBBBNT.js} +1 -1
  3. package/dist/chunks/{add-U4WWFW6A.js → add-QNZUJVW3.js} +1 -1
  4. package/dist/chunks/{build-62AFJDRZ.js → build-KKE7LLGT.js} +1 -1
  5. package/dist/chunks/{chunk-BAHTCIMJ.js → chunk-24L6BDAY.js} +1 -1
  6. package/dist/chunks/{chunk-FJPYSIUV.js → chunk-2CDYSI2W.js} +1 -1
  7. package/dist/chunks/{chunk-PUNGYINC.js → chunk-3CK5SHI4.js} +1 -1
  8. package/dist/chunks/{chunk-H3HSH5FW.js → chunk-3TOEU3F6.js} +1 -1
  9. package/dist/chunks/{chunk-XCEO6325.js → chunk-4ZZEDEMN.js} +1 -1
  10. package/dist/chunks/{chunk-YBE2G3LP.js → chunk-5KLSANRW.js} +1 -1
  11. package/dist/chunks/{chunk-DBPL6EVR.js → chunk-5NRYTFUS.js} +1 -1
  12. package/dist/chunks/{chunk-T52PWZNS.js → chunk-5VVIXI7N.js} +1 -1
  13. package/dist/chunks/{chunk-JMJ2FVX3.js → chunk-6562FIUX.js} +1 -1
  14. package/dist/chunks/{chunk-EEH7JGGG.js → chunk-67H6BT7B.js} +1 -1
  15. package/dist/chunks/{chunk-2I4XYW65.js → chunk-BSPLBWAX.js} +1 -1
  16. package/dist/chunks/{chunk-MUCHLKSG.js → chunk-DPQLHYC5.js} +1 -1
  17. package/dist/chunks/{chunk-55EEFTI7.js → chunk-DSFXR6UL.js} +1 -1
  18. package/dist/chunks/{chunk-PVXBOZ45.js → chunk-EYH6WGF2.js} +1 -1
  19. package/dist/chunks/{chunk-E7R5SQDA.js → chunk-FEO3KPCN.js} +2 -2
  20. package/dist/chunks/{chunk-2A7TTZJ4.js → chunk-FRBBC5I7.js} +1 -1
  21. package/dist/chunks/{chunk-OIIOMP67.js → chunk-GIRRO4QV.js} +1 -1
  22. package/dist/chunks/{chunk-GGRFONYT.js → chunk-GJQ3G7OG.js} +1 -1
  23. package/dist/chunks/{chunk-CYBPBS37.js → chunk-GROKZBM5.js} +1 -1
  24. package/dist/chunks/{chunk-CMAZDLNJ.js → chunk-GVQEICZZ.js} +1 -1
  25. package/dist/chunks/{chunk-R3BZ4IDA.js → chunk-GXTN6ATK.js} +1 -1
  26. package/dist/chunks/{chunk-VTA5KIL5.js → chunk-H3K7IR5S.js} +1 -1
  27. package/dist/chunks/{chunk-TAIREW55.js → chunk-H3NVQYY6.js} +1 -1
  28. package/dist/chunks/{chunk-4U2H6XBH.js → chunk-HCFEUT2S.js} +1 -1
  29. package/dist/chunks/{chunk-JJ4DOHP4.js → chunk-HH7YFAAX.js} +1 -1
  30. package/dist/chunks/{chunk-BVHXBPKR.js → chunk-HHV7F6W4.js} +1 -1
  31. package/dist/chunks/{chunk-CEJO447T.js → chunk-HOYNGN6Y.js} +1 -1
  32. package/dist/chunks/{chunk-OBSOJQH7.js → chunk-I3EXVLOR.js} +1 -1
  33. package/dist/chunks/{chunk-KVX64ZHU.js → chunk-IXRTZRJN.js} +1 -1
  34. package/dist/chunks/{chunk-WBYRQHSP.js → chunk-JZXT53LT.js} +1 -1
  35. package/dist/chunks/{chunk-Y7JAJKAJ.js → chunk-KNQPKVDP.js} +1 -1
  36. package/dist/chunks/{chunk-26HAXM56.js → chunk-KTWVMMXL.js} +1 -1
  37. package/dist/chunks/{chunk-HPYP2LC3.js → chunk-LCM7GAHQ.js} +1 -1
  38. package/dist/chunks/{chunk-J3DYBDSK.js → chunk-MDSJKFYU.js} +1 -1
  39. package/dist/chunks/{chunk-MADCVSMW.js → chunk-MHIH4NVP.js} +1 -1
  40. package/dist/chunks/{chunk-O5RWOOY4.js → chunk-MSKKM36B.js} +1 -1
  41. package/dist/chunks/{chunk-H4BQDKOU.js → chunk-MUJDAD73.js} +4 -4
  42. package/dist/chunks/{chunk-GEBGZ3EG.js → chunk-N4J3R7KS.js} +1 -1
  43. package/dist/chunks/{chunk-IFSD556O.js → chunk-NBMLJM3J.js} +1 -1
  44. package/dist/chunks/{chunk-Q45WRPBA.js → chunk-NNYSREF6.js} +1 -1
  45. package/dist/chunks/{chunk-3RPOSTE4.js → chunk-NZU43SVD.js} +1 -1
  46. package/dist/chunks/{chunk-ALRMGYWE.js → chunk-OCIRBXJK.js} +1 -1
  47. package/dist/chunks/{chunk-VNTREJRW.js → chunk-OHK7TSWE.js} +1 -1
  48. package/dist/chunks/{chunk-AHAT5QYP.js → chunk-PYXGCPOE.js} +1 -1
  49. package/dist/chunks/{chunk-7VFMF2X2.js → chunk-SP73R4DW.js} +1 -1
  50. package/dist/chunks/{chunk-ZJTN7U74.js → chunk-SUZXGVMN.js} +1 -1
  51. package/dist/chunks/{chunk-4KEWLHYF.js → chunk-TTGD6NBN.js} +1 -1
  52. package/dist/chunks/{chunk-VZX47KDU.js → chunk-TTSA4CGZ.js} +1 -1
  53. package/dist/chunks/{chunk-Z3QJKD32.js → chunk-TXQFB44P.js} +1 -1
  54. package/dist/chunks/{chunk-M345GUX4.js → chunk-UL6BYW6P.js} +1 -1
  55. package/dist/chunks/{chunk-Q4WSTT5G.js → chunk-V2BCAK3I.js} +1 -1
  56. package/dist/chunks/{chunk-EYSD2ULB.js → chunk-W6KIUTKO.js} +1 -1
  57. package/dist/chunks/{chunk-ILX4D2PP.js → chunk-X2LS3YDZ.js} +1 -1
  58. package/dist/chunks/{chunk-5KTOBHJR.js → chunk-XJVTGNAB.js} +1 -1
  59. package/dist/chunks/{chunk-S5TWKTHV.js → chunk-XTDL6VDZ.js} +1 -1
  60. package/dist/chunks/{chunk-WYSNAEMX.js → chunk-YDWOGOYQ.js} +1 -1
  61. package/dist/chunks/{chunk-CM2HJYDA.js → chunk-YSOO56PM.js} +1 -1
  62. package/dist/chunks/{chunk-UITNWLE7.js → chunk-Z7B7PFAR.js} +2 -2
  63. package/dist/chunks/{chunk-XRCHG3IF.js → chunk-ZZTCTVBJ.js} +1 -1
  64. package/dist/chunks/{clear-JOCTJFHZ.js → clear-CHK647GV.js} +1 -1
  65. package/dist/chunks/{compile-vercel-config-H5MLKZB5.js → compile-vercel-config-HAQYXHPB.js} +1 -1
  66. package/dist/chunks/{config-4IL23FDT.js → config-ROLBZC3E.js} +1 -1
  67. package/dist/chunks/{config-WY56RPZJ.js → config-X6N2ECGU.js} +1 -1
  68. package/dist/chunks/{delete-SN7E5MTV.js → delete-A3ZN3JL2.js} +1 -1
  69. package/dist/chunks/{delete-PWULSIJU.js → delete-MC7BC7NX.js} +1 -1
  70. package/dist/chunks/{describe-II22LJP3.js → describe-MF3QA4XP.js} +1 -1
  71. package/dist/chunks/{detect-services-VIJ4XLRR.js → detect-services-V6P6RNRY.js} +1 -1
  72. package/dist/chunks/{disable-7PWT4ILT.js → disable-GKANXOTL.js} +1 -1
  73. package/dist/chunks/{discard-GL42ZPA7.js → discard-2WY2RBN3.js} +1 -1
  74. package/dist/chunks/{edit-JCJDO73Y.js → edit-DXAJX6I2.js} +1 -1
  75. package/dist/chunks/{edit-SJH6BCRY.js → edit-U4VYAWI2.js} +1 -1
  76. package/dist/chunks/{enable-G7RZ5VV4.js → enable-LLHUA7RH.js} +1 -1
  77. package/dist/chunks/{export-CUKYNL3C.js → export-4DW4AQ46.js} +1 -1
  78. package/dist/chunks/{future-PAAXGZTN.js → future-WJEMZHER.js} +1 -1
  79. package/dist/chunks/{generate-cert-for-deploy-ZAMSUCFF.js → generate-cert-for-deploy-EHPJUMRI.js} +1 -1
  80. package/dist/chunks/{group-actions-O76SXUUJ.js → group-actions-MVWNYISJ.js} +1 -1
  81. package/dist/chunks/{image-QDQO36EW.js → image-XXG2UE6K.js} +1 -1
  82. package/dist/chunks/{import-builders-EFVZQWHA.js → import-builders-JZ2W4AKZ.js} +1 -1
  83. package/dist/chunks/{inspect-XYVW6J2E.js → inspect-23F7OG7O.js} +1 -1
  84. package/dist/chunks/{inspect-AGC7W3OS.js → inspect-2YUBT5J7.js} +1 -1
  85. package/dist/chunks/{inspect-KPAFRFZA.js → inspect-CMX764GE.js} +1 -1
  86. package/dist/chunks/{inspect-BSLSCH4L.js → inspect-FBFB4673.js} +1 -1
  87. package/dist/chunks/{inspect-XXQ7X2W7.js → inspect-NIW6SLTJ.js} +1 -1
  88. package/dist/chunks/{list-X6EO34N6.js → list-4HCIH7ZT.js} +1 -1
  89. package/dist/chunks/{list-RYYPFUX4.js → list-5EN5BQGX.js} +1 -1
  90. package/dist/chunks/{list-2KYHARKO.js → list-LBLSWS4G.js} +1 -1
  91. package/dist/chunks/{login-6VVAMBOA.js → login-7B6WUTZA.js} +1 -1
  92. package/dist/chunks/{login-IPMI6XEL.js → login-FCE6ZNVP.js} +1 -1
  93. package/dist/chunks/{logs-UQPPRXTB.js → logs-UCFAA573.js} +1 -1
  94. package/dist/chunks/{ls-QQ3F6OJ3.js → ls-22KCD6XH.js} +1 -1
  95. package/dist/chunks/{ls-WRJ6GDUR.js → ls-74UF3GAZ.js} +1 -1
  96. package/dist/chunks/{ls-5SH4HSZ5.js → ls-AFD7VVPV.js} +1 -1
  97. package/dist/chunks/{ls-KAPV4POT.js → ls-JF5IEJRG.js} +1 -1
  98. package/dist/chunks/{ls-6GPP7PTK.js → ls-M3AULXSF.js} +1 -1
  99. package/dist/chunks/{ls-FR5KWP4I.js → ls-TZVW6K64.js} +1 -1
  100. package/dist/chunks/{ls-KITNPWDE.js → ls-VX6NJEQ5.js} +1 -1
  101. package/dist/chunks/{migrate-experimental-services-BORV5SUM.js → migrate-experimental-services-DPLTGN7G.js} +1 -1
  102. package/dist/chunks/{mutate-TER55VAA.js → mutate-ANP4MINN.js} +1 -1
  103. package/dist/chunks/{notifications-SUB7P4EX.js → notifications-ZLM75IM7.js} +1 -1
  104. package/dist/chunks/{open-GANU5JWA.js → open-BTVG7PAR.js} +1 -1
  105. package/dist/chunks/{permissions-V4UHHOV2.js → permissions-R2VXNC7P.js} +1 -1
  106. package/dist/chunks/{plugin-offer-SFFLTT66.js → plugin-offer-TOGG57CN.js} +1 -1
  107. package/dist/chunks/{prompt-missing-credentials-CVIIFJ6S.js → prompt-missing-credentials-M3MJ23CT.js} +1 -1
  108. package/dist/chunks/{publish-MV3RCHJM.js → publish-ZE5QH5IK.js} +1 -1
  109. package/dist/chunks/{pull-JGTNLAF3.js → pull-THZVVRD5.js} +1 -1
  110. package/dist/chunks/{purchase-domain-if-available-OO533ARB.js → purchase-domain-if-available-JCYJIHA3.js} +1 -1
  111. package/dist/chunks/{push-FJZEB3K2.js → push-3IMAJJIA.js} +1 -1
  112. package/dist/chunks/{query-3HB7DLVE.js → query-JS46X4HV.js} +1 -1
  113. package/dist/chunks/{raw-query-PNZO3D3S.js → raw-query-4K6JHAQG.js} +1 -1
  114. package/dist/chunks/{reauthenticate-6TPAZX5R.js → reauthenticate-5WD77AFG.js} +1 -1
  115. package/dist/chunks/{remove-76ZLLEHO.js → remove-KOF4XIZ7.js} +1 -1
  116. package/dist/chunks/{reorder-ZZRQMWQO.js → reorder-3NXXZRZO.js} +1 -1
  117. package/dist/chunks/{reply-LWX3Q77Y.js → reply-JNYYMJN5.js} +1 -1
  118. package/dist/chunks/{resolve-K72DNP5D.js → resolve-RGGB7NDY.js} +1 -1
  119. package/dist/chunks/{resolve-agent-team-75QSXK3C.js → resolve-agent-team-ZB6AGD4A.js} +1 -1
  120. package/dist/chunks/{restore-CMVVFIY3.js → restore-7TLQ4OQL.js} +1 -1
  121. package/dist/chunks/{rm-7Q6CRYDP.js → rm-GG4YAYEG.js} +1 -1
  122. package/dist/chunks/{rm-TELAXNYE.js → rm-GKRLNTNG.js} +1 -1
  123. package/dist/chunks/{rm-KGIBQFXK.js → rm-LVENOOH4.js} +1 -1
  124. package/dist/chunks/{rm-4W2E3LPX.js → rm-NUEUIXWD.js} +1 -1
  125. package/dist/chunks/{rm-MRH5RXBQ.js → rm-TR7263R7.js} +1 -1
  126. package/dist/chunks/{rule-inspect-2Z7XXWVB.js → rule-inspect-7VXXJWNZ.js} +1 -1
  127. package/dist/chunks/{schema-QAYQPSHG.js → schema-HCNHCZ3R.js} +1 -1
  128. package/dist/chunks/{schema-5OJQWJJ6.js → schema-LZGI5ZTU.js} +1 -1
  129. package/dist/chunks/{select-org-CRZAHEXQ.js → select-org-HKSE2YDF.js} +1 -1
  130. package/dist/chunks/{set-AQP6ILFQ.js → set-7UNVXHZM.js} +1 -1
  131. package/dist/chunks/{setup-and-link-EFNAHZR4.js → setup-and-link-L47YL6MP.js} +1 -1
  132. package/dist/chunks/{tags-EHN3GJUF.js → tags-NXBLJZJF.js} +1 -1
  133. package/dist/chunks/{update-2CVWFAVE.js → update-BCBWJ565.js} +1 -1
  134. package/dist/chunks/{usage-LE5BHDUT.js → usage-G4CJ3ZOH.js} +1 -1
  135. package/dist/chunks/{views-AKV4QHMO.js → views-QU3K2TSP.js} +1 -1
  136. package/dist/commands/build/index.js +1 -1
  137. package/dist/commands/deploy/index.js +5 -5
  138. package/dist/commands/dev/index.js +2 -2
  139. package/dist/commands/env/index.js +1 -1
  140. package/dist/commands/link/index.js +1 -1
  141. package/dist/commands/list/index.js +1 -1
  142. package/dist/commands/project/index.js +1 -1
  143. package/dist/commands/tunnel/index.js +1 -1
  144. package/dist/commands-account.js +2 -2
  145. package/dist/commands-ai.js +1 -1
  146. package/dist/commands-blob.js +1 -1
  147. package/dist/commands-core.js +5 -5
  148. package/dist/commands-deployments.js +1 -1
  149. package/dist/commands-flags.js +1 -1
  150. package/dist/commands-integrations.js +1 -1
  151. package/dist/commands-observability.js +2 -2
  152. package/dist/commands-routing.js +2 -2
  153. package/dist/index.js +3 -3
  154. package/dist/internal-build.js +1 -1
  155. package/dist/package.json +40 -40
  156. package/dist/version.mjs +1 -1
  157. package/package.json +42 -42
@@ -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-VZX47KDU.js";import{loadVercelConfig,tryDetectServices}from"../../chunks/chunk-ILX4D2PP.js";import"../../chunks/chunk-QIVM5MTP.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-4U2H6XBH.js";import{createErrorReporter,import_write_build_result,require_detect_builders_with_services,require_get_files,require_mime_types,require_service_schedules}from"../../chunks/chunk-CM2HJYDA.js";import{importBuilders,require_npa,require_static_builder}from"../../chunks/chunk-M345GUX4.js";import"../../chunks/chunk-4CACOKMS.js";import"../../chunks/chunk-MX66ZGZL.js";import{validateConfig}from"../../chunks/chunk-VSWANERN.js";import{DevCommandExitError,ServiceStartError,announceTunnel,checkForPort,dev,formatTunnelError,materializeRuntimeAsset,runTunnel,telemetryCodes,toDiagnostic,waitForPortToFree}from"../../chunks/chunk-WYSNAEMX.js";import"../../chunks/chunk-3GKXXGSO.js";import{decodeJwt}from"../../chunks/chunk-QNMWYJQW.js";import{require_fast_deep_equal}from"../../chunks/chunk-IMLHRJ4K.js";import{LOCAL_SCHEDULES_SESSION_HEADER,createLocalSchedulesSession}from"../../chunks/chunk-XPEWDJV6.js";import"../../chunks/chunk-ZD3CDFPZ.js";import"../../chunks/chunk-BNWEJZAC.js";import{pickOverrides}from"../../chunks/chunk-EEH7JGGG.js";import"../../chunks/chunk-ALRMGYWE.js";import"../../chunks/chunk-C2R5IEN6.js";import{require_main}from"../../chunks/chunk-26HAXM56.js";import{getUpdateCommand}from"../../chunks/chunk-CYBPBS37.js";import{isNativeBinaryInstall}from"../../chunks/chunk-5F4RJ32E.js";import{readJSONFile}from"../../chunks/chunk-3RPOSTE4.js";import"../../chunks/chunk-DXFQOBXB.js";import"../../chunks/chunk-4L7AKIX7.js";import"../../chunks/chunk-X5YKQ2RJ.js";import"../../chunks/chunk-N7IBUNFY.js";import"../../chunks/chunk-37SWAKIV.js";import{getEnabledProtection}from"../../chunks/chunk-VNS4Z72T.js";import"../../chunks/chunk-VT6RIZJH.js";import"../../chunks/chunk-XKVKG7CW.js";import"../../chunks/chunk-T52PWZNS.js";import"../../chunks/chunk-6G2AZBW5.js";import{require_raw_body}from"../../chunks/chunk-CHY2NJU4.js";import"../../chunks/chunk-3WXQHKSS.js";import{external_exports}from"../../chunks/chunk-64GNDWWX.js";import{require_dist as require_dist5}from"../../chunks/chunk-P5TIDWPF.js";import{require_brace_expansion,require_minimatch}from"../../chunks/chunk-VQAIH2X5.js";import{require_dist as require_dist4}from"../../chunks/chunk-MN2F4NPH.js";import{VERCEL_OIDC_TOKEN}from"../../chunks/chunk-PUNGYINC.js";import{pullEnvRecords}from"../../chunks/chunk-AHAT5QYP.js";import{require_frameworks}from"../../chunks/chunk-I254SHTL.js";import"../../chunks/chunk-KR4DMT3I.js";import"../../chunks/chunk-7IHVCKUV.js";import"../../chunks/chunk-55EEFTI7.js";import"../../chunks/chunk-R3BZ4IDA.js";import"../../chunks/chunk-7YKFF6CE.js";import"../../chunks/chunk-3HP6FOOL.js";import"../../chunks/chunk-IZV6K7RR.js";import"../../chunks/chunk-O256QMQM.js";import{require_json_parse_better_errors}from"../../chunks/chunk-K7YK4PZP.js";import"../../chunks/chunk-CSU46B7Q.js";import"../../chunks/chunk-O5RWOOY4.js";import"../../chunks/chunk-UITNWLE7.js";import{printProjectNotFoundError}from"../../chunks/chunk-HPYP2LC3.js";import"../../chunks/chunk-I3QZSYRK.js";import"../../chunks/chunk-BV456GI7.js";import"../../chunks/chunk-TAAWMNNL.js";import"../../chunks/chunk-RFD7CEL6.js";import"../../chunks/chunk-ILNTOWHG.js";import"../../chunks/chunk-IQ7FPAI4.js";import"../../chunks/chunk-237WN2MK.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-QCYCLWNG.js";import"../../chunks/chunk-HPXRESOF.js";import{param}from"../../chunks/chunk-ERMHTPO4.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-EZ3HXFLB.js";import{require_dist as require_dist2}from"../../chunks/chunk-WMIZ6Y4E.js";import"../../chunks/chunk-QPNYOR6O.js";import{detectExplicitScope}from"../../chunks/chunk-H3HSH5FW.js";import{TelemetryClient}from"../../chunks/chunk-QROPMCL2.js";import{VERCEL_DIR,findRepoRoot,getLinkedProject,getLocalPathConfig,getVercelDirectory,highlight,localConfigFlagPath,require_dist2 as require_dist3,require_lib,resolveProjectCwd}from"../../chunks/chunk-H4BQDKOU.js";import{printAlignedLabel}from"../../chunks/chunk-SUD5V67L.js";import{require_pluralize}from"../../chunks/chunk-7TRHPXCG.js";import"../../chunks/chunk-VO5M6G7M.js";import"../../chunks/chunk-QRPBDCDH.js";import"../../chunks/chunk-2GXP676X.js";import"../../chunks/chunk-K5GE24PG.js";import"../../chunks/chunk-IFMPBA4K.js";import"../../chunks/chunk-KHJWQ4WP.js";import{directFetch}from"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-YATYCZQJ.js";import{require_ms}from"../../chunks/chunk-2ILZM77F.js";import{printError}from"../../chunks/chunk-QI7BWXRV.js";import{parseArguments}from"../../chunks/chunk-E7ICSU45.js";import{buildCommandWithYes,outputActionRequired}from"../../chunks/chunk-3QTP26QS.js";import{warnDeprecatedSubcommand}from"../../chunks/chunk-BDLZ6WL2.js";import"../../chunks/chunk-PH2MLBQO.js";import"../../chunks/chunk-DCFCPAFQ.js";import"../../chunks/chunk-GOXGA37R.js";import{CantParseJSONFile,LambdaSizeExceededError,MissingDotenvVarsError,NowError,require_bytes}from"../../chunks/chunk-UNAQQ5DF.js";import{cmd,getCommandName,getCommandNamePlain,getTitleName}from"../../chunks/chunk-EFGZK6OY.js";import{pkg_default}from"../../chunks/chunk-JCDPMWKO.js";import{link_default,output_manager_default}from"../../chunks/chunk-RIXTYUYN.js";import"../../chunks/chunk-7Y572CPZ.js";import{require_build_utils}from"../../chunks/chunk-BVFFSUG3.js";import"../../chunks/chunk-RRX2AMWY.js";import"../../chunks/chunk-GUFRGEM5.js";import"../../chunks/chunk-SUT2PTL3.js";import"../../chunks/chunk-AX6UCTOC.js";import{require_dist}from"../../chunks/chunk-4SIQE2W4.js";import"../../chunks/chunk-MF43WTDT.js";import{help}from"../../chunks/chunk-7TREJIPV.js";import"../../chunks/chunk-7QHUMMBA.js";import"../../chunks/chunk-AUCQKYL2.js";import{getFlagsSpecification}from"../../chunks/chunk-CUO3CYU3.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-UJ7YUIEJ.js";import"../../chunks/chunk-L6MWUMWZ.js";import"../../chunks/chunk-L4CSJDG7.js";import"../../chunks/chunk-YHZXIBS7.js";import"../../chunks/chunk-LPYHYTYI.js";import{__commonJS,__require,__toESM}from"../../chunks/chunk-NBPLUP7C.js";var require_eventemitter3=__commonJS({"../../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(exports,module){"use strict";var has=Object.prototype.hasOwnProperty,prefix="~";function Events(){}Object.create&&(Events.prototype=Object.create(null),new Events().__proto__||(prefix=!1));function EE(fn,context,once2){this.fn=fn,this.context=context,this.once=once2||!1}function addListener(emitter,event,fn,context,once2){if(typeof fn!="function")throw new TypeError("The listener must be a function");var listener=new EE(fn,context||emitter,once2),evt=prefix?prefix+event:event;return emitter._events[evt]?emitter._events[evt].fn?emitter._events[evt]=[emitter._events[evt],listener]:emitter._events[evt].push(listener):(emitter._events[evt]=listener,emitter._eventsCount++),emitter}function clearEvent(emitter,evt){--emitter._eventsCount===0?emitter._events=new Events:delete emitter._events[evt]}function EventEmitter(){this._events=new Events,this._eventsCount=0}EventEmitter.prototype.eventNames=function(){var names=[],events,name;if(this._eventsCount===0)return names;for(name in events=this._events)has.call(events,name)&&names.push(prefix?name.slice(1):name);return Object.getOwnPropertySymbols?names.concat(Object.getOwnPropertySymbols(events)):names};EventEmitter.prototype.listeners=function(event){var evt=prefix?prefix+event:event,handlers=this._events[evt];if(!handlers)return[];if(handlers.fn)return[handlers.fn];for(var i=0,l=handlers.length,ee=new Array(l);i<l;i++)ee[i]=handlers[i].fn;return ee};EventEmitter.prototype.listenerCount=function(event){var evt=prefix?prefix+event:event,listeners=this._events[evt];return listeners?listeners.fn?1:listeners.length:0};EventEmitter.prototype.emit=function(event,a1,a2,a3,a4,a5){var evt=prefix?prefix+event:event;if(!this._events[evt])return!1;var listeners=this._events[evt],len=arguments.length,args,i;if(listeners.fn){switch(listeners.once&&this.removeListener(event,listeners.fn,void 0,!0),len){case 1:return listeners.fn.call(listeners.context),!0;case 2:return listeners.fn.call(listeners.context,a1),!0;case 3:return listeners.fn.call(listeners.context,a1,a2),!0;case 4:return listeners.fn.call(listeners.context,a1,a2,a3),!0;case 5:return listeners.fn.call(listeners.context,a1,a2,a3,a4),!0;case 6:return listeners.fn.call(listeners.context,a1,a2,a3,a4,a5),!0}for(i=1,args=new Array(len-1);i<len;i++)args[i-1]=arguments[i];listeners.fn.apply(listeners.context,args)}else{var length=listeners.length,j;for(i=0;i<length;i++)switch(listeners[i].once&&this.removeListener(event,listeners[i].fn,void 0,!0),len){case 1:listeners[i].fn.call(listeners[i].context);break;case 2:listeners[i].fn.call(listeners[i].context,a1);break;case 3:listeners[i].fn.call(listeners[i].context,a1,a2);break;case 4:listeners[i].fn.call(listeners[i].context,a1,a2,a3);break;default:if(!args)for(j=1,args=new Array(len-1);j<len;j++)args[j-1]=arguments[j];listeners[i].fn.apply(listeners[i].context,args)}}return!0};EventEmitter.prototype.on=function(event,fn,context){return addListener(this,event,fn,context,!1)};EventEmitter.prototype.once=function(event,fn,context){return addListener(this,event,fn,context,!0)};EventEmitter.prototype.removeListener=function(event,fn,context,once2){var evt=prefix?prefix+event:event;if(!this._events[evt])return this;if(!fn)return clearEvent(this,evt),this;var listeners=this._events[evt];if(listeners.fn)listeners.fn===fn&&(!once2||listeners.once)&&(!context||listeners.context===context)&&clearEvent(this,evt);else{for(var i=0,events=[],length=listeners.length;i<length;i++)(listeners[i].fn!==fn||once2&&!listeners[i].once||context&&listeners[i].context!==context)&&events.push(listeners[i]);events.length?this._events[evt]=events.length===1?events[0]:events:clearEvent(this,evt)}return this};EventEmitter.prototype.removeAllListeners=function(event){var evt;return event?(evt=prefix?prefix+event:event,this._events[evt]&&clearEvent(this,evt)):(this._events=new Events,this._eventsCount=0),this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prefixed=prefix;EventEmitter.EventEmitter=EventEmitter;typeof module<"u"&&(module.exports=EventEmitter)}});var require_requires_port=__commonJS({"../../node_modules/.pnpm/requires-port@1.0.0/node_modules/requires-port/index.js"(exports,module){"use strict";module.exports=function(port,protocol){if(protocol=protocol.split(":")[0],port=+port,!port)return!1;switch(protocol){case"http":case"ws":return port!==80;case"https":case"wss":return port!==443;case"ftp":return port!==21;case"gopher":return port!==70;case"file":return!1}return port!==0}}});var require_common=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@4.4.3/node_modules/http-proxy-node16/lib/http-proxy/common.js"(exports){var common=exports,url4=__require("url"),extend=Object.assign,required=require_requires_port(),upgradeHeader=/(^|,)\s*upgrade\s*($|,)/i,isSSL=/^https|wss/;common.isSSL=isSSL;common.setupOutgoing=function(outgoing,options,req,forward){outgoing.port=options[forward||"target"].port||(isSSL.test(options[forward||"target"].protocol)?443:80),["host","hostname","socketPath","pfx","key","passphrase","cert","ca","ciphers","secureProtocol"].forEach(function(e){outgoing[e]=options[forward||"target"][e]}),outgoing.method=options.method||req.method,outgoing.headers=extend({},req.headers),options.headers&&extend(outgoing.headers,options.headers),options.auth&&(outgoing.auth=options.auth),options.ca&&(outgoing.ca=options.ca),isSSL.test(options[forward||"target"].protocol)&&(outgoing.rejectUnauthorized=typeof options.secure>"u"?!0:options.secure),outgoing.agent=options.agent||!1,outgoing.localAddress=options.localAddress,outgoing.agent||(outgoing.headers=outgoing.headers||{},(typeof outgoing.headers.connection!="string"||!upgradeHeader.test(outgoing.headers.connection))&&(outgoing.headers.connection="close"));var target=options[forward||"target"],targetPath=target&&options.prependPath!==!1&&target.path||"",outgoingPath=options.toProxy?req.url:url4.parse(req.url).path||"";return outgoingPath=options.ignorePath?"":outgoingPath,outgoing.path=common.urlJoin(targetPath,outgoingPath),options.changeOrigin&&(outgoing.headers.host=required(outgoing.port,options[forward||"target"].protocol)&&!hasPort(outgoing.host)?outgoing.host+":"+outgoing.port:outgoing.host),outgoing};common.setupSocket=function(socket){return socket.setTimeout(0),socket.setNoDelay(!0),socket.setKeepAlive(!0,0),socket};common.getPort=function(req){var res=req.headers.host?req.headers.host.match(/:(\d+)/):"";return res?res[1]:common.hasEncryptedConnection(req)?"443":"80"};common.hasEncryptedConnection=function(req){return!!(req.connection.encrypted||req.connection.pair)};common.urlJoin=function(){var args=Array.prototype.slice.call(arguments),queryParams=[],queryParamRaw="",retSegs;return args.forEach((url5,index)=>{var qpStart=url5.indexOf("?");qpStart!==-1&&(queryParams.push(url5.substring(qpStart+1)),args[index]=url5.substring(0,qpStart))}),queryParamRaw=queryParams.filter(Boolean).join("&"),retSegs=args.filter(Boolean).join("/").replace(/\/+/g,"/").replace("http:/","http://").replace("https:/","https://"),queryParamRaw?retSegs+"?"+queryParamRaw:retSegs};common.rewriteCookieProperty=function rewriteCookieProperty(header,config,property){return Array.isArray(header)?header.map(function(headerElement){return rewriteCookieProperty(headerElement,config,property)}):header.replace(new RegExp("(;\\s*"+property+"=)([^;]+)","i"),function(match,prefix,previousValue){var newValue;if(previousValue in config)newValue=config[previousValue];else if("*"in config)newValue=config["*"];else return match;return newValue?prefix+newValue:""})};function hasPort(host){return!!~host.indexOf(":")}}});var require_web_outgoing=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@4.4.3/node_modules/http-proxy-node16/lib/http-proxy/passes/web-outgoing.js"(exports,module){var url4=__require("url"),common=require_common(),redirectRegex=/^201|30(1|2|7|8)$/;module.exports={removeChunked:function(req,res,proxyRes){req.httpVersion==="1.0"&&delete proxyRes.headers["transfer-encoding"]},setConnection:function(req,res,proxyRes){req.httpVersion==="1.0"?proxyRes.headers.connection=req.headers.connection||"close":req.httpVersion!=="2.0"&&!proxyRes.headers.connection&&(proxyRes.headers.connection=req.headers.connection||"keep-alive")},setRedirectHostRewrite:function(req,res,proxyRes,options){if((options.hostRewrite||options.autoRewrite||options.protocolRewrite)&&proxyRes.headers.location&&redirectRegex.test(proxyRes.statusCode)){var target=url4.parse(options.target),u=url4.parse(proxyRes.headers.location);if(target.host!=u.host)return;options.hostRewrite?u.host=options.hostRewrite:options.autoRewrite&&(u.host=req.headers.host),options.protocolRewrite&&(u.protocol=options.protocolRewrite),proxyRes.headers.location=u.format()}},writeHeaders:function(req,res,proxyRes,options){var rewriteCookieDomainConfig=options.cookieDomainRewrite,rewriteCookiePathConfig=options.cookiePathRewrite,preserveHeaderKeyCase=options.preserveHeaderKeyCase,rawHeaderKeyMap,setHeader=function(key2,header){header!=null&&(rewriteCookieDomainConfig&&key2.toLowerCase()==="set-cookie"&&(header=common.rewriteCookieProperty(header,rewriteCookieDomainConfig,"domain")),rewriteCookiePathConfig&&key2.toLowerCase()==="set-cookie"&&(header=common.rewriteCookieProperty(header,rewriteCookiePathConfig,"path")),res.setHeader(String(key2).trim(),header))};if(typeof rewriteCookieDomainConfig=="string"&&(rewriteCookieDomainConfig={"*":rewriteCookieDomainConfig}),typeof rewriteCookiePathConfig=="string"&&(rewriteCookiePathConfig={"*":rewriteCookiePathConfig}),preserveHeaderKeyCase&&proxyRes.rawHeaders!=null){rawHeaderKeyMap={};for(var i=0;i<proxyRes.rawHeaders.length;i+=2){var key=proxyRes.rawHeaders[i];rawHeaderKeyMap[key.toLowerCase()]=key}}Object.keys(proxyRes.headers).forEach(function(key2){var header=proxyRes.headers[key2];preserveHeaderKeyCase&&rawHeaderKeyMap&&(key2=rawHeaderKeyMap[key2]||key2),setHeader(key2,header)})},writeStatusCode:function(req,res,proxyRes){proxyRes.statusMessage?(res.statusCode=proxyRes.statusCode,res.statusMessage=proxyRes.statusMessage):res.statusCode=proxyRes.statusCode}}}});var require_debug=__commonJS({"../../node_modules/.pnpm/follow-redirects@1.16.0_debug@4.4.3/node_modules/follow-redirects/debug.js"(exports,module){var debug;module.exports=function(){if(!debug){try{debug=__require("debug")("follow-redirects")}catch{}typeof debug!="function"&&(debug=function(){})}debug.apply(null,arguments)}}});var require_follow_redirects=__commonJS({"../../node_modules/.pnpm/follow-redirects@1.16.0_debug@4.4.3/node_modules/follow-redirects/index.js"(exports,module){var url4=__require("url"),URL3=url4.URL,http2=__require("http"),https=__require("https"),Writable2=__require("stream").Writable,assert=__require("assert"),debug=require_debug();(function(){var looksLikeNode=typeof process<"u",looksLikeBrowser=typeof window<"u"&&typeof document<"u",looksLikeV8=isFunction(Error.captureStackTrace);!looksLikeNode&&(looksLikeBrowser||!looksLikeV8)&&console.warn("The follow-redirects package should be excluded from browser builds.")})();var useNativeURL=!1;try{assert(new URL3(""))}catch(error2){useNativeURL=error2.code==="ERR_INVALID_URL"}var sensitiveHeaders=["Authorization","Proxy-Authorization","Cookie"],preservedUrlFields=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],events=["abort","aborted","connect","error","socket","timeout"],eventHandlers=Object.create(null);events.forEach(function(event){eventHandlers[event]=function(arg1,arg2,arg3){this._redirectable.emit(event,arg1,arg2,arg3)}});var InvalidUrlError=createErrorType("ERR_INVALID_URL","Invalid URL",TypeError),RedirectionError=createErrorType("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),TooManyRedirectsError=createErrorType("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",RedirectionError),MaxBodyLengthExceededError=createErrorType("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),WriteAfterEndError=createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),destroy=Writable2.prototype.destroy||noop;function RedirectableRequest(options,responseCallback){Writable2.call(this),this._sanitizeOptions(options),this._options=options,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],responseCallback&&this.on("response",responseCallback);var self2=this;this._onNativeResponse=function(response){try{self2._processResponse(response)}catch(cause){self2.emit("error",cause instanceof RedirectionError?cause:new RedirectionError({cause}))}},this._headerFilter=new RegExp("^(?:"+sensitiveHeaders.concat(options.sensitiveHeaders).map(escapeRegex).join("|")+")$","i"),this._performRequest()}RedirectableRequest.prototype=Object.create(Writable2.prototype);RedirectableRequest.prototype.abort=function(){destroyRequest(this._currentRequest),this._currentRequest.abort(),this.emit("abort")};RedirectableRequest.prototype.destroy=function(error2){return destroyRequest(this._currentRequest,error2),destroy.call(this,error2),this};RedirectableRequest.prototype.write=function(data,encoding,callback){if(this._ending)throw new WriteAfterEndError;if(!isString(data)&&!isBuffer(data))throw new TypeError("data should be a string, Buffer or Uint8Array");if(isFunction(encoding)&&(callback=encoding,encoding=null),data.length===0){callback&&callback();return}this._requestBodyLength+data.length<=this._options.maxBodyLength?(this._requestBodyLength+=data.length,this._requestBodyBuffers.push({data,encoding}),this._currentRequest.write(data,encoding,callback)):(this.emit("error",new MaxBodyLengthExceededError),this.abort())};RedirectableRequest.prototype.end=function(data,encoding,callback){if(isFunction(data)?(callback=data,data=encoding=null):isFunction(encoding)&&(callback=encoding,encoding=null),!data)this._ended=this._ending=!0,this._currentRequest.end(null,null,callback);else{var self2=this,currentRequest=this._currentRequest;this.write(data,encoding,function(){self2._ended=!0,currentRequest.end(null,null,callback)}),this._ending=!0}};RedirectableRequest.prototype.setHeader=function(name,value){this._options.headers[name]=value,this._currentRequest.setHeader(name,value)};RedirectableRequest.prototype.removeHeader=function(name){delete this._options.headers[name],this._currentRequest.removeHeader(name)};RedirectableRequest.prototype.setTimeout=function(msecs,callback){var self2=this;function destroyOnTimeout(socket){socket.setTimeout(msecs),socket.removeListener("timeout",socket.destroy),socket.addListener("timeout",socket.destroy)}function startTimer(socket){self2._timeout&&clearTimeout(self2._timeout),self2._timeout=setTimeout(function(){self2.emit("timeout"),clearTimer()},msecs),destroyOnTimeout(socket)}function clearTimer(){self2._timeout&&(clearTimeout(self2._timeout),self2._timeout=null),self2.removeListener("abort",clearTimer),self2.removeListener("error",clearTimer),self2.removeListener("response",clearTimer),self2.removeListener("close",clearTimer),callback&&self2.removeListener("timeout",callback),self2.socket||self2._currentRequest.removeListener("socket",startTimer)}return callback&&this.on("timeout",callback),this.socket?startTimer(this.socket):this._currentRequest.once("socket",startTimer),this.on("socket",destroyOnTimeout),this.on("abort",clearTimer),this.on("error",clearTimer),this.on("response",clearTimer),this.on("close",clearTimer),this};["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(method){RedirectableRequest.prototype[method]=function(a,b){return this._currentRequest[method](a,b)}});["aborted","connection","socket"].forEach(function(property){Object.defineProperty(RedirectableRequest.prototype,property,{get:function(){return this._currentRequest[property]}})});RedirectableRequest.prototype._sanitizeOptions=function(options){if(options.headers||(options.headers={}),isArray(options.sensitiveHeaders)||(options.sensitiveHeaders=[]),options.host&&(options.hostname||(options.hostname=options.host),delete options.host),!options.pathname&&options.path){var searchPos=options.path.indexOf("?");searchPos<0?options.pathname=options.path:(options.pathname=options.path.substring(0,searchPos),options.search=options.path.substring(searchPos))}};RedirectableRequest.prototype._performRequest=function(){var protocol=this._options.protocol,nativeProtocol=this._options.nativeProtocols[protocol];if(!nativeProtocol)throw new TypeError("Unsupported protocol "+protocol);if(this._options.agents){var scheme=protocol.slice(0,-1);this._options.agent=this._options.agents[scheme]}var request=this._currentRequest=nativeProtocol.request(this._options,this._onNativeResponse);request._redirectable=this;for(var event of events)request.on(event,eventHandlers[event]);if(this._currentUrl=/^\//.test(this._options.path)?url4.format(this._options):this._options.path,this._isRedirect){var i=0,self2=this,buffers=this._requestBodyBuffers;(function writeNext(error2){if(request===self2._currentRequest)if(error2)self2.emit("error",error2);else if(i<buffers.length){var buffer=buffers[i++];request.finished||request.write(buffer.data,buffer.encoding,writeNext)}else self2._ended&&request.end()})()}};RedirectableRequest.prototype._processResponse=function(response){var statusCode=response.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:response.headers,statusCode});var location=response.headers.location;if(!location||this._options.followRedirects===!1||statusCode<300||statusCode>=400){response.responseUrl=this._currentUrl,response.redirects=this._redirects,this.emit("response",response),this._requestBodyBuffers=[];return}if(destroyRequest(this._currentRequest),response.destroy(),++this._redirectCount>this._options.maxRedirects)throw new TooManyRedirectsError;var requestHeaders,beforeRedirect=this._options.beforeRedirect;beforeRedirect&&(requestHeaders=Object.assign({Host:response.req.getHeader("host")},this._options.headers));var method=this._options.method;((statusCode===301||statusCode===302)&&this._options.method==="POST"||statusCode===303&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],removeMatchingHeaders(/^content-/i,this._options.headers));var currentHostHeader=removeMatchingHeaders(/^host$/i,this._options.headers),currentUrlParts=parseUrl2(this._currentUrl),currentHost=currentHostHeader||currentUrlParts.host,currentUrl=/^\w+:/.test(location)?this._currentUrl:url4.format(Object.assign(currentUrlParts,{host:currentHost})),redirectUrl=resolveUrl(location,currentUrl);if(debug("redirecting to",redirectUrl.href),this._isRedirect=!0,spreadUrlObject(redirectUrl,this._options),(redirectUrl.protocol!==currentUrlParts.protocol&&redirectUrl.protocol!=="https:"||redirectUrl.host!==currentHost&&!isSubdomain(redirectUrl.host,currentHost))&&removeMatchingHeaders(this._headerFilter,this._options.headers),isFunction(beforeRedirect)){var responseDetails={headers:response.headers,statusCode},requestDetails={url:currentUrl,method,headers:requestHeaders};beforeRedirect(this._options,responseDetails,requestDetails),this._sanitizeOptions(this._options)}this._performRequest()};function wrap(protocols){var exports2={maxRedirects:21,maxBodyLength:10485760},nativeProtocols={};return Object.keys(protocols).forEach(function(scheme){var protocol=scheme+":",nativeProtocol=nativeProtocols[protocol]=protocols[scheme],wrappedProtocol=exports2[scheme]=Object.create(nativeProtocol);function request(input,options,callback){return isURL2(input)?input=spreadUrlObject(input):isString(input)?input=spreadUrlObject(parseUrl2(input)):(callback=options,options=validateUrl(input),input={protocol}),isFunction(options)&&(callback=options,options=null),options=Object.assign({maxRedirects:exports2.maxRedirects,maxBodyLength:exports2.maxBodyLength},input,options),options.nativeProtocols=nativeProtocols,!isString(options.host)&&!isString(options.hostname)&&(options.hostname="::1"),assert.equal(options.protocol,protocol,"protocol mismatch"),debug("options",options),new RedirectableRequest(options,callback)}function get(input,options,callback){var wrappedRequest=wrappedProtocol.request(input,options,callback);return wrappedRequest.end(),wrappedRequest}Object.defineProperties(wrappedProtocol,{request:{value:request,configurable:!0,enumerable:!0,writable:!0},get:{value:get,configurable:!0,enumerable:!0,writable:!0}})}),exports2}function noop(){}function parseUrl2(input){var parsed;if(useNativeURL)parsed=new URL3(input);else if(parsed=validateUrl(url4.parse(input)),!isString(parsed.protocol))throw new InvalidUrlError({input});return parsed}function resolveUrl(relative3,base){return useNativeURL?new URL3(relative3,base):parseUrl2(url4.resolve(base,relative3))}function validateUrl(input){if(/^\[/.test(input.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(input.hostname))throw new InvalidUrlError({input:input.href||input});if(/^\[/.test(input.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host))throw new InvalidUrlError({input:input.href||input});return input}function spreadUrlObject(urlObject,target){var spread=target||{};for(var key of preservedUrlFields)spread[key]=urlObject[key];return spread.hostname.startsWith("[")&&(spread.hostname=spread.hostname.slice(1,-1)),spread.port!==""&&(spread.port=Number(spread.port)),spread.path=spread.search?spread.pathname+spread.search:spread.pathname,spread}function removeMatchingHeaders(regex,headers){var lastValue;for(var header in headers)regex.test(header)&&(lastValue=headers[header],delete headers[header]);return lastValue===null||typeof lastValue>"u"?void 0:String(lastValue).trim()}function createErrorType(code,message,baseClass){function CustomError(properties){isFunction(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,properties||{}),this.code=code,this.message=this.cause?message+": "+this.cause.message:message}return CustomError.prototype=new(baseClass||Error),Object.defineProperties(CustomError.prototype,{constructor:{value:CustomError,enumerable:!1},name:{value:"Error ["+code+"]",enumerable:!1}}),CustomError}function destroyRequest(request,error2){for(var event of events)request.removeListener(event,eventHandlers[event]);request.on("error",noop),request.destroy(error2)}function isSubdomain(subdomain,domain){assert(isString(subdomain)&&isString(domain));var dot=subdomain.length-domain.length-1;return dot>0&&subdomain[dot]==="."&&subdomain.endsWith(domain)}function isArray(value){return value instanceof Array}function isString(value){return typeof value=="string"||value instanceof String}function isFunction(value){return typeof value=="function"}function isBuffer(value){return typeof value=="object"&&"length"in value}function isURL2(value){return URL3&&value instanceof URL3}function escapeRegex(regex){return regex.replace(/[\]\\/()*+?.$]/g,"\\$&")}module.exports=wrap({http:http2,https});module.exports.wrap=wrap}});var require_web_incoming=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@4.4.3/node_modules/http-proxy-node16/lib/http-proxy/passes/web-incoming.js"(exports,module){var httpNative=__require("http"),httpsNative=__require("https"),web_o=require_web_outgoing(),common=require_common(),followRedirects=require_follow_redirects();web_o=Object.keys(web_o).map(function(pass){return web_o[pass]});var nativeAgents={http:httpNative,https:httpsNative};var supportsAbortedEvent=function(){var ver=process.versions.node.split(".").map(Number);return ver[0]<=14||ver[0]===15&&ver[1]<=4}();module.exports={deleteLength:function(req,res,options){(req.method==="DELETE"||req.method==="OPTIONS")&&!req.headers["content-length"]&&(req.headers["content-length"]="0",delete req.headers["transfer-encoding"])},timeout:function(req,res,options){options.timeout&&req.socket.setTimeout(options.timeout)},XHeaders:function(req,res,options){if(options.xfwd){var encrypted=req.isSpdy||common.hasEncryptedConnection(req),values={for:req.connection.remoteAddress||req.socket.remoteAddress,port:common.getPort(req),proto:encrypted?"https":"http"};["for","port","proto"].forEach(function(header){req.headers["x-forwarded-"+header]=(req.headers["x-forwarded-"+header]||"")+(req.headers["x-forwarded-"+header]?",":"")+values[header]}),req.headers["x-forwarded-host"]=req.headers["x-forwarded-host"]||req.headers.host||""}},stream:function(req,res,options,_,server,clb){server.emit("start",req,res,options.target||options.forward);var agents=options.followRedirects?followRedirects:nativeAgents,http2=agents.http,https=agents.https;if(options.forward){var forwardReq=(options.forward.protocol==="https:"?https:http2).request(common.setupOutgoing(options.ssl||{},options,req,"forward")),forwardError=createErrorHandler(forwardReq,options.forward);if(req.on("error",forwardError),forwardReq.on("error",forwardError),(options.buffer||req).pipe(forwardReq),!options.target)return res.end()}var proxyReq=(options.target.protocol==="https:"?https:http2).request(common.setupOutgoing(options.ssl||{},options,req));proxyReq.on("socket",function(socket){server&&!proxyReq.getHeader("expect")&&server.emit("proxyReq",proxyReq,req,res,options)}),options.proxyTimeout&&proxyReq.setTimeout(options.proxyTimeout,function(){proxyReq.abort()}),supportsAbortedEvent?req.on("aborted",function(){proxyReq.abort()}):res.on("close",function(){var aborted=!res.writableFinished;aborted&&proxyReq.abort()});var proxyError=createErrorHandler(proxyReq,options.target);req.on("error",proxyError),proxyReq.on("error",proxyError);function createErrorHandler(proxyReq2,url4){return function(err){if(req.socket.destroyed&&err.code==="ECONNRESET")return server.emit("econnreset",err,req,res,url4),proxyReq2.abort();clb?clb(err,req,res,url4):server.emit("error",err,req,res,url4)}}(options.buffer||req).pipe(proxyReq),proxyReq.on("response",function(proxyRes){if(server&&server.emit("proxyRes",proxyRes,req,res),!res.headersSent&&!options.selfHandleResponse)for(var i=0;i<web_o.length&&!web_o[i](req,res,proxyRes,options);i++);res.finished?server&&server.emit("end",req,res,proxyRes):(proxyRes.on("end",function(){server&&server.emit("end",req,res,proxyRes)}),options.selfHandleResponse||proxyRes.pipe(res))})}}}});var require_ws_incoming=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@4.4.3/node_modules/http-proxy-node16/lib/http-proxy/passes/ws-incoming.js"(exports,module){var http2=__require("http"),https=__require("https"),common=require_common();module.exports={checkMethodAndHeader:function(req,socket){if(req.method!=="GET"||!req.headers.upgrade||req.headers.upgrade.toLowerCase()!=="websocket")return socket.destroy(),!0},XHeaders:function(req,socket,options){if(options.xfwd){var values={for:req.connection.remoteAddress||req.socket.remoteAddress,port:common.getPort(req),proto:common.hasEncryptedConnection(req)?"wss":"ws"};["for","port","proto"].forEach(function(header){req.headers["x-forwarded-"+header]=(req.headers["x-forwarded-"+header]||"")+(req.headers["x-forwarded-"+header]?",":"")+values[header]})}},stream:function(req,socket,options,head,server,clb){var createHttpHeader=function(line,headers){return Object.keys(headers).reduce(function(head2,key){var value=headers[key];if(!Array.isArray(value))return head2.push(key+": "+value),head2;for(var i=0;i<value.length;i++)head2.push(key+": "+value[i]);return head2},[line]).join(`\r
7
+ import{displayDetectedServices,readConfig,setupAndLink}from"../../chunks/chunk-TTSA4CGZ.js";import{loadVercelConfig,tryDetectServices}from"../../chunks/chunk-X2LS3YDZ.js";import"../../chunks/chunk-QIVM5MTP.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-HCFEUT2S.js";import{createErrorReporter,import_write_build_result,require_detect_builders_with_services,require_get_files,require_mime_types,require_service_schedules}from"../../chunks/chunk-YSOO56PM.js";import{importBuilders,require_npa,require_static_builder}from"../../chunks/chunk-UL6BYW6P.js";import"../../chunks/chunk-4CACOKMS.js";import"../../chunks/chunk-MX66ZGZL.js";import{validateConfig}from"../../chunks/chunk-VSWANERN.js";import{DevCommandExitError,ServiceStartError,announceTunnel,checkForPort,dev,formatTunnelError,materializeRuntimeAsset,runTunnel,telemetryCodes,toDiagnostic,waitForPortToFree}from"../../chunks/chunk-YDWOGOYQ.js";import"../../chunks/chunk-3GKXXGSO.js";import{decodeJwt}from"../../chunks/chunk-QNMWYJQW.js";import{require_fast_deep_equal}from"../../chunks/chunk-IMLHRJ4K.js";import{LOCAL_SCHEDULES_SESSION_HEADER,createLocalSchedulesSession}from"../../chunks/chunk-XPEWDJV6.js";import"../../chunks/chunk-ZD3CDFPZ.js";import"../../chunks/chunk-BNWEJZAC.js";import{pickOverrides}from"../../chunks/chunk-67H6BT7B.js";import"../../chunks/chunk-OCIRBXJK.js";import"../../chunks/chunk-C2R5IEN6.js";import{require_main}from"../../chunks/chunk-KTWVMMXL.js";import{getUpdateCommand}from"../../chunks/chunk-GROKZBM5.js";import{isNativeBinaryInstall}from"../../chunks/chunk-5F4RJ32E.js";import{readJSONFile}from"../../chunks/chunk-NZU43SVD.js";import"../../chunks/chunk-DXFQOBXB.js";import"../../chunks/chunk-4L7AKIX7.js";import"../../chunks/chunk-X5YKQ2RJ.js";import"../../chunks/chunk-N7IBUNFY.js";import"../../chunks/chunk-37SWAKIV.js";import{getEnabledProtection}from"../../chunks/chunk-VNS4Z72T.js";import"../../chunks/chunk-VT6RIZJH.js";import"../../chunks/chunk-XKVKG7CW.js";import"../../chunks/chunk-5VVIXI7N.js";import"../../chunks/chunk-6G2AZBW5.js";import{require_raw_body}from"../../chunks/chunk-CHY2NJU4.js";import"../../chunks/chunk-3WXQHKSS.js";import{external_exports}from"../../chunks/chunk-64GNDWWX.js";import{require_dist as require_dist5}from"../../chunks/chunk-P5TIDWPF.js";import{require_brace_expansion,require_minimatch}from"../../chunks/chunk-VQAIH2X5.js";import{require_dist as require_dist4}from"../../chunks/chunk-MN2F4NPH.js";import{VERCEL_OIDC_TOKEN}from"../../chunks/chunk-3CK5SHI4.js";import{pullEnvRecords}from"../../chunks/chunk-PYXGCPOE.js";import{require_frameworks}from"../../chunks/chunk-I254SHTL.js";import"../../chunks/chunk-KR4DMT3I.js";import"../../chunks/chunk-7IHVCKUV.js";import"../../chunks/chunk-DSFXR6UL.js";import"../../chunks/chunk-GXTN6ATK.js";import"../../chunks/chunk-7YKFF6CE.js";import"../../chunks/chunk-3HP6FOOL.js";import"../../chunks/chunk-IZV6K7RR.js";import"../../chunks/chunk-O256QMQM.js";import{require_json_parse_better_errors}from"../../chunks/chunk-K7YK4PZP.js";import"../../chunks/chunk-CSU46B7Q.js";import"../../chunks/chunk-MSKKM36B.js";import"../../chunks/chunk-Z7B7PFAR.js";import{printProjectNotFoundError}from"../../chunks/chunk-LCM7GAHQ.js";import"../../chunks/chunk-I3QZSYRK.js";import"../../chunks/chunk-BV456GI7.js";import"../../chunks/chunk-TAAWMNNL.js";import"../../chunks/chunk-RFD7CEL6.js";import"../../chunks/chunk-ILNTOWHG.js";import"../../chunks/chunk-IQ7FPAI4.js";import"../../chunks/chunk-237WN2MK.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-QCYCLWNG.js";import"../../chunks/chunk-HPXRESOF.js";import{param}from"../../chunks/chunk-ERMHTPO4.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-EZ3HXFLB.js";import{require_dist as require_dist2}from"../../chunks/chunk-WMIZ6Y4E.js";import"../../chunks/chunk-QPNYOR6O.js";import{detectExplicitScope}from"../../chunks/chunk-3TOEU3F6.js";import{TelemetryClient}from"../../chunks/chunk-QROPMCL2.js";import{VERCEL_DIR,findRepoRoot,getLinkedProject,getLocalPathConfig,getVercelDirectory,highlight,localConfigFlagPath,require_dist2 as require_dist3,require_lib,resolveProjectCwd}from"../../chunks/chunk-MUJDAD73.js";import{printAlignedLabel}from"../../chunks/chunk-SUD5V67L.js";import{require_pluralize}from"../../chunks/chunk-7TRHPXCG.js";import"../../chunks/chunk-VO5M6G7M.js";import"../../chunks/chunk-QRPBDCDH.js";import"../../chunks/chunk-2GXP676X.js";import"../../chunks/chunk-K5GE24PG.js";import"../../chunks/chunk-IFMPBA4K.js";import"../../chunks/chunk-KHJWQ4WP.js";import{directFetch}from"../../chunks/chunk-MY4MONOH.js";import"../../chunks/chunk-YATYCZQJ.js";import{require_ms}from"../../chunks/chunk-2ILZM77F.js";import{printError}from"../../chunks/chunk-QI7BWXRV.js";import{parseArguments}from"../../chunks/chunk-E7ICSU45.js";import{buildCommandWithYes,outputActionRequired}from"../../chunks/chunk-3QTP26QS.js";import{warnDeprecatedSubcommand}from"../../chunks/chunk-BDLZ6WL2.js";import"../../chunks/chunk-PH2MLBQO.js";import"../../chunks/chunk-DCFCPAFQ.js";import"../../chunks/chunk-GOXGA37R.js";import{CantParseJSONFile,LambdaSizeExceededError,MissingDotenvVarsError,NowError,require_bytes}from"../../chunks/chunk-UNAQQ5DF.js";import{cmd,getCommandName,getCommandNamePlain,getTitleName}from"../../chunks/chunk-EFGZK6OY.js";import{pkg_default}from"../../chunks/chunk-JCDPMWKO.js";import{link_default,output_manager_default}from"../../chunks/chunk-RIXTYUYN.js";import"../../chunks/chunk-7Y572CPZ.js";import{require_build_utils}from"../../chunks/chunk-BVFFSUG3.js";import"../../chunks/chunk-RRX2AMWY.js";import"../../chunks/chunk-GUFRGEM5.js";import"../../chunks/chunk-SUT2PTL3.js";import"../../chunks/chunk-AX6UCTOC.js";import{require_dist}from"../../chunks/chunk-4SIQE2W4.js";import"../../chunks/chunk-MF43WTDT.js";import{help}from"../../chunks/chunk-7TREJIPV.js";import"../../chunks/chunk-7QHUMMBA.js";import"../../chunks/chunk-AUCQKYL2.js";import{getFlagsSpecification}from"../../chunks/chunk-CUO3CYU3.js";import"../../chunks/chunk-2BKALEOP.js";import{require_source}from"../../chunks/chunk-UJ7YUIEJ.js";import"../../chunks/chunk-L6MWUMWZ.js";import"../../chunks/chunk-L4CSJDG7.js";import"../../chunks/chunk-YHZXIBS7.js";import"../../chunks/chunk-LPYHYTYI.js";import{__commonJS,__require,__toESM}from"../../chunks/chunk-NBPLUP7C.js";var require_eventemitter3=__commonJS({"../../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(exports,module){"use strict";var has=Object.prototype.hasOwnProperty,prefix="~";function Events(){}Object.create&&(Events.prototype=Object.create(null),new Events().__proto__||(prefix=!1));function EE(fn,context,once2){this.fn=fn,this.context=context,this.once=once2||!1}function addListener(emitter,event,fn,context,once2){if(typeof fn!="function")throw new TypeError("The listener must be a function");var listener=new EE(fn,context||emitter,once2),evt=prefix?prefix+event:event;return emitter._events[evt]?emitter._events[evt].fn?emitter._events[evt]=[emitter._events[evt],listener]:emitter._events[evt].push(listener):(emitter._events[evt]=listener,emitter._eventsCount++),emitter}function clearEvent(emitter,evt){--emitter._eventsCount===0?emitter._events=new Events:delete emitter._events[evt]}function EventEmitter(){this._events=new Events,this._eventsCount=0}EventEmitter.prototype.eventNames=function(){var names=[],events,name;if(this._eventsCount===0)return names;for(name in events=this._events)has.call(events,name)&&names.push(prefix?name.slice(1):name);return Object.getOwnPropertySymbols?names.concat(Object.getOwnPropertySymbols(events)):names};EventEmitter.prototype.listeners=function(event){var evt=prefix?prefix+event:event,handlers=this._events[evt];if(!handlers)return[];if(handlers.fn)return[handlers.fn];for(var i=0,l=handlers.length,ee=new Array(l);i<l;i++)ee[i]=handlers[i].fn;return ee};EventEmitter.prototype.listenerCount=function(event){var evt=prefix?prefix+event:event,listeners=this._events[evt];return listeners?listeners.fn?1:listeners.length:0};EventEmitter.prototype.emit=function(event,a1,a2,a3,a4,a5){var evt=prefix?prefix+event:event;if(!this._events[evt])return!1;var listeners=this._events[evt],len=arguments.length,args,i;if(listeners.fn){switch(listeners.once&&this.removeListener(event,listeners.fn,void 0,!0),len){case 1:return listeners.fn.call(listeners.context),!0;case 2:return listeners.fn.call(listeners.context,a1),!0;case 3:return listeners.fn.call(listeners.context,a1,a2),!0;case 4:return listeners.fn.call(listeners.context,a1,a2,a3),!0;case 5:return listeners.fn.call(listeners.context,a1,a2,a3,a4),!0;case 6:return listeners.fn.call(listeners.context,a1,a2,a3,a4,a5),!0}for(i=1,args=new Array(len-1);i<len;i++)args[i-1]=arguments[i];listeners.fn.apply(listeners.context,args)}else{var length=listeners.length,j;for(i=0;i<length;i++)switch(listeners[i].once&&this.removeListener(event,listeners[i].fn,void 0,!0),len){case 1:listeners[i].fn.call(listeners[i].context);break;case 2:listeners[i].fn.call(listeners[i].context,a1);break;case 3:listeners[i].fn.call(listeners[i].context,a1,a2);break;case 4:listeners[i].fn.call(listeners[i].context,a1,a2,a3);break;default:if(!args)for(j=1,args=new Array(len-1);j<len;j++)args[j-1]=arguments[j];listeners[i].fn.apply(listeners[i].context,args)}}return!0};EventEmitter.prototype.on=function(event,fn,context){return addListener(this,event,fn,context,!1)};EventEmitter.prototype.once=function(event,fn,context){return addListener(this,event,fn,context,!0)};EventEmitter.prototype.removeListener=function(event,fn,context,once2){var evt=prefix?prefix+event:event;if(!this._events[evt])return this;if(!fn)return clearEvent(this,evt),this;var listeners=this._events[evt];if(listeners.fn)listeners.fn===fn&&(!once2||listeners.once)&&(!context||listeners.context===context)&&clearEvent(this,evt);else{for(var i=0,events=[],length=listeners.length;i<length;i++)(listeners[i].fn!==fn||once2&&!listeners[i].once||context&&listeners[i].context!==context)&&events.push(listeners[i]);events.length?this._events[evt]=events.length===1?events[0]:events:clearEvent(this,evt)}return this};EventEmitter.prototype.removeAllListeners=function(event){var evt;return event?(evt=prefix?prefix+event:event,this._events[evt]&&clearEvent(this,evt)):(this._events=new Events,this._eventsCount=0),this};EventEmitter.prototype.off=EventEmitter.prototype.removeListener;EventEmitter.prototype.addListener=EventEmitter.prototype.on;EventEmitter.prefixed=prefix;EventEmitter.EventEmitter=EventEmitter;typeof module<"u"&&(module.exports=EventEmitter)}});var require_requires_port=__commonJS({"../../node_modules/.pnpm/requires-port@1.0.0/node_modules/requires-port/index.js"(exports,module){"use strict";module.exports=function(port,protocol){if(protocol=protocol.split(":")[0],port=+port,!port)return!1;switch(protocol){case"http":case"ws":return port!==80;case"https":case"wss":return port!==443;case"ftp":return port!==21;case"gopher":return port!==70;case"file":return!1}return port!==0}}});var require_common=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@4.4.3/node_modules/http-proxy-node16/lib/http-proxy/common.js"(exports){var common=exports,url4=__require("url"),extend=Object.assign,required=require_requires_port(),upgradeHeader=/(^|,)\s*upgrade\s*($|,)/i,isSSL=/^https|wss/;common.isSSL=isSSL;common.setupOutgoing=function(outgoing,options,req,forward){outgoing.port=options[forward||"target"].port||(isSSL.test(options[forward||"target"].protocol)?443:80),["host","hostname","socketPath","pfx","key","passphrase","cert","ca","ciphers","secureProtocol"].forEach(function(e){outgoing[e]=options[forward||"target"][e]}),outgoing.method=options.method||req.method,outgoing.headers=extend({},req.headers),options.headers&&extend(outgoing.headers,options.headers),options.auth&&(outgoing.auth=options.auth),options.ca&&(outgoing.ca=options.ca),isSSL.test(options[forward||"target"].protocol)&&(outgoing.rejectUnauthorized=typeof options.secure>"u"?!0:options.secure),outgoing.agent=options.agent||!1,outgoing.localAddress=options.localAddress,outgoing.agent||(outgoing.headers=outgoing.headers||{},(typeof outgoing.headers.connection!="string"||!upgradeHeader.test(outgoing.headers.connection))&&(outgoing.headers.connection="close"));var target=options[forward||"target"],targetPath=target&&options.prependPath!==!1&&target.path||"",outgoingPath=options.toProxy?req.url:url4.parse(req.url).path||"";return outgoingPath=options.ignorePath?"":outgoingPath,outgoing.path=common.urlJoin(targetPath,outgoingPath),options.changeOrigin&&(outgoing.headers.host=required(outgoing.port,options[forward||"target"].protocol)&&!hasPort(outgoing.host)?outgoing.host+":"+outgoing.port:outgoing.host),outgoing};common.setupSocket=function(socket){return socket.setTimeout(0),socket.setNoDelay(!0),socket.setKeepAlive(!0,0),socket};common.getPort=function(req){var res=req.headers.host?req.headers.host.match(/:(\d+)/):"";return res?res[1]:common.hasEncryptedConnection(req)?"443":"80"};common.hasEncryptedConnection=function(req){return!!(req.connection.encrypted||req.connection.pair)};common.urlJoin=function(){var args=Array.prototype.slice.call(arguments),queryParams=[],queryParamRaw="",retSegs;return args.forEach((url5,index)=>{var qpStart=url5.indexOf("?");qpStart!==-1&&(queryParams.push(url5.substring(qpStart+1)),args[index]=url5.substring(0,qpStart))}),queryParamRaw=queryParams.filter(Boolean).join("&"),retSegs=args.filter(Boolean).join("/").replace(/\/+/g,"/").replace("http:/","http://").replace("https:/","https://"),queryParamRaw?retSegs+"?"+queryParamRaw:retSegs};common.rewriteCookieProperty=function rewriteCookieProperty(header,config,property){return Array.isArray(header)?header.map(function(headerElement){return rewriteCookieProperty(headerElement,config,property)}):header.replace(new RegExp("(;\\s*"+property+"=)([^;]+)","i"),function(match,prefix,previousValue){var newValue;if(previousValue in config)newValue=config[previousValue];else if("*"in config)newValue=config["*"];else return match;return newValue?prefix+newValue:""})};function hasPort(host){return!!~host.indexOf(":")}}});var require_web_outgoing=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@4.4.3/node_modules/http-proxy-node16/lib/http-proxy/passes/web-outgoing.js"(exports,module){var url4=__require("url"),common=require_common(),redirectRegex=/^201|30(1|2|7|8)$/;module.exports={removeChunked:function(req,res,proxyRes){req.httpVersion==="1.0"&&delete proxyRes.headers["transfer-encoding"]},setConnection:function(req,res,proxyRes){req.httpVersion==="1.0"?proxyRes.headers.connection=req.headers.connection||"close":req.httpVersion!=="2.0"&&!proxyRes.headers.connection&&(proxyRes.headers.connection=req.headers.connection||"keep-alive")},setRedirectHostRewrite:function(req,res,proxyRes,options){if((options.hostRewrite||options.autoRewrite||options.protocolRewrite)&&proxyRes.headers.location&&redirectRegex.test(proxyRes.statusCode)){var target=url4.parse(options.target),u=url4.parse(proxyRes.headers.location);if(target.host!=u.host)return;options.hostRewrite?u.host=options.hostRewrite:options.autoRewrite&&(u.host=req.headers.host),options.protocolRewrite&&(u.protocol=options.protocolRewrite),proxyRes.headers.location=u.format()}},writeHeaders:function(req,res,proxyRes,options){var rewriteCookieDomainConfig=options.cookieDomainRewrite,rewriteCookiePathConfig=options.cookiePathRewrite,preserveHeaderKeyCase=options.preserveHeaderKeyCase,rawHeaderKeyMap,setHeader=function(key2,header){header!=null&&(rewriteCookieDomainConfig&&key2.toLowerCase()==="set-cookie"&&(header=common.rewriteCookieProperty(header,rewriteCookieDomainConfig,"domain")),rewriteCookiePathConfig&&key2.toLowerCase()==="set-cookie"&&(header=common.rewriteCookieProperty(header,rewriteCookiePathConfig,"path")),res.setHeader(String(key2).trim(),header))};if(typeof rewriteCookieDomainConfig=="string"&&(rewriteCookieDomainConfig={"*":rewriteCookieDomainConfig}),typeof rewriteCookiePathConfig=="string"&&(rewriteCookiePathConfig={"*":rewriteCookiePathConfig}),preserveHeaderKeyCase&&proxyRes.rawHeaders!=null){rawHeaderKeyMap={};for(var i=0;i<proxyRes.rawHeaders.length;i+=2){var key=proxyRes.rawHeaders[i];rawHeaderKeyMap[key.toLowerCase()]=key}}Object.keys(proxyRes.headers).forEach(function(key2){var header=proxyRes.headers[key2];preserveHeaderKeyCase&&rawHeaderKeyMap&&(key2=rawHeaderKeyMap[key2]||key2),setHeader(key2,header)})},writeStatusCode:function(req,res,proxyRes){proxyRes.statusMessage?(res.statusCode=proxyRes.statusCode,res.statusMessage=proxyRes.statusMessage):res.statusCode=proxyRes.statusCode}}}});var require_debug=__commonJS({"../../node_modules/.pnpm/follow-redirects@1.16.0_debug@4.4.3/node_modules/follow-redirects/debug.js"(exports,module){var debug;module.exports=function(){if(!debug){try{debug=__require("debug")("follow-redirects")}catch{}typeof debug!="function"&&(debug=function(){})}debug.apply(null,arguments)}}});var require_follow_redirects=__commonJS({"../../node_modules/.pnpm/follow-redirects@1.16.0_debug@4.4.3/node_modules/follow-redirects/index.js"(exports,module){var url4=__require("url"),URL3=url4.URL,http2=__require("http"),https=__require("https"),Writable2=__require("stream").Writable,assert=__require("assert"),debug=require_debug();(function(){var looksLikeNode=typeof process<"u",looksLikeBrowser=typeof window<"u"&&typeof document<"u",looksLikeV8=isFunction(Error.captureStackTrace);!looksLikeNode&&(looksLikeBrowser||!looksLikeV8)&&console.warn("The follow-redirects package should be excluded from browser builds.")})();var useNativeURL=!1;try{assert(new URL3(""))}catch(error2){useNativeURL=error2.code==="ERR_INVALID_URL"}var sensitiveHeaders=["Authorization","Proxy-Authorization","Cookie"],preservedUrlFields=["auth","host","hostname","href","path","pathname","port","protocol","query","search","hash"],events=["abort","aborted","connect","error","socket","timeout"],eventHandlers=Object.create(null);events.forEach(function(event){eventHandlers[event]=function(arg1,arg2,arg3){this._redirectable.emit(event,arg1,arg2,arg3)}});var InvalidUrlError=createErrorType("ERR_INVALID_URL","Invalid URL",TypeError),RedirectionError=createErrorType("ERR_FR_REDIRECTION_FAILURE","Redirected request failed"),TooManyRedirectsError=createErrorType("ERR_FR_TOO_MANY_REDIRECTS","Maximum number of redirects exceeded",RedirectionError),MaxBodyLengthExceededError=createErrorType("ERR_FR_MAX_BODY_LENGTH_EXCEEDED","Request body larger than maxBodyLength limit"),WriteAfterEndError=createErrorType("ERR_STREAM_WRITE_AFTER_END","write after end"),destroy=Writable2.prototype.destroy||noop;function RedirectableRequest(options,responseCallback){Writable2.call(this),this._sanitizeOptions(options),this._options=options,this._ended=!1,this._ending=!1,this._redirectCount=0,this._redirects=[],this._requestBodyLength=0,this._requestBodyBuffers=[],responseCallback&&this.on("response",responseCallback);var self2=this;this._onNativeResponse=function(response){try{self2._processResponse(response)}catch(cause){self2.emit("error",cause instanceof RedirectionError?cause:new RedirectionError({cause}))}},this._headerFilter=new RegExp("^(?:"+sensitiveHeaders.concat(options.sensitiveHeaders).map(escapeRegex).join("|")+")$","i"),this._performRequest()}RedirectableRequest.prototype=Object.create(Writable2.prototype);RedirectableRequest.prototype.abort=function(){destroyRequest(this._currentRequest),this._currentRequest.abort(),this.emit("abort")};RedirectableRequest.prototype.destroy=function(error2){return destroyRequest(this._currentRequest,error2),destroy.call(this,error2),this};RedirectableRequest.prototype.write=function(data,encoding,callback){if(this._ending)throw new WriteAfterEndError;if(!isString(data)&&!isBuffer(data))throw new TypeError("data should be a string, Buffer or Uint8Array");if(isFunction(encoding)&&(callback=encoding,encoding=null),data.length===0){callback&&callback();return}this._requestBodyLength+data.length<=this._options.maxBodyLength?(this._requestBodyLength+=data.length,this._requestBodyBuffers.push({data,encoding}),this._currentRequest.write(data,encoding,callback)):(this.emit("error",new MaxBodyLengthExceededError),this.abort())};RedirectableRequest.prototype.end=function(data,encoding,callback){if(isFunction(data)?(callback=data,data=encoding=null):isFunction(encoding)&&(callback=encoding,encoding=null),!data)this._ended=this._ending=!0,this._currentRequest.end(null,null,callback);else{var self2=this,currentRequest=this._currentRequest;this.write(data,encoding,function(){self2._ended=!0,currentRequest.end(null,null,callback)}),this._ending=!0}};RedirectableRequest.prototype.setHeader=function(name,value){this._options.headers[name]=value,this._currentRequest.setHeader(name,value)};RedirectableRequest.prototype.removeHeader=function(name){delete this._options.headers[name],this._currentRequest.removeHeader(name)};RedirectableRequest.prototype.setTimeout=function(msecs,callback){var self2=this;function destroyOnTimeout(socket){socket.setTimeout(msecs),socket.removeListener("timeout",socket.destroy),socket.addListener("timeout",socket.destroy)}function startTimer(socket){self2._timeout&&clearTimeout(self2._timeout),self2._timeout=setTimeout(function(){self2.emit("timeout"),clearTimer()},msecs),destroyOnTimeout(socket)}function clearTimer(){self2._timeout&&(clearTimeout(self2._timeout),self2._timeout=null),self2.removeListener("abort",clearTimer),self2.removeListener("error",clearTimer),self2.removeListener("response",clearTimer),self2.removeListener("close",clearTimer),callback&&self2.removeListener("timeout",callback),self2.socket||self2._currentRequest.removeListener("socket",startTimer)}return callback&&this.on("timeout",callback),this.socket?startTimer(this.socket):this._currentRequest.once("socket",startTimer),this.on("socket",destroyOnTimeout),this.on("abort",clearTimer),this.on("error",clearTimer),this.on("response",clearTimer),this.on("close",clearTimer),this};["flushHeaders","getHeader","setNoDelay","setSocketKeepAlive"].forEach(function(method){RedirectableRequest.prototype[method]=function(a,b){return this._currentRequest[method](a,b)}});["aborted","connection","socket"].forEach(function(property){Object.defineProperty(RedirectableRequest.prototype,property,{get:function(){return this._currentRequest[property]}})});RedirectableRequest.prototype._sanitizeOptions=function(options){if(options.headers||(options.headers={}),isArray(options.sensitiveHeaders)||(options.sensitiveHeaders=[]),options.host&&(options.hostname||(options.hostname=options.host),delete options.host),!options.pathname&&options.path){var searchPos=options.path.indexOf("?");searchPos<0?options.pathname=options.path:(options.pathname=options.path.substring(0,searchPos),options.search=options.path.substring(searchPos))}};RedirectableRequest.prototype._performRequest=function(){var protocol=this._options.protocol,nativeProtocol=this._options.nativeProtocols[protocol];if(!nativeProtocol)throw new TypeError("Unsupported protocol "+protocol);if(this._options.agents){var scheme=protocol.slice(0,-1);this._options.agent=this._options.agents[scheme]}var request=this._currentRequest=nativeProtocol.request(this._options,this._onNativeResponse);request._redirectable=this;for(var event of events)request.on(event,eventHandlers[event]);if(this._currentUrl=/^\//.test(this._options.path)?url4.format(this._options):this._options.path,this._isRedirect){var i=0,self2=this,buffers=this._requestBodyBuffers;(function writeNext(error2){if(request===self2._currentRequest)if(error2)self2.emit("error",error2);else if(i<buffers.length){var buffer=buffers[i++];request.finished||request.write(buffer.data,buffer.encoding,writeNext)}else self2._ended&&request.end()})()}};RedirectableRequest.prototype._processResponse=function(response){var statusCode=response.statusCode;this._options.trackRedirects&&this._redirects.push({url:this._currentUrl,headers:response.headers,statusCode});var location=response.headers.location;if(!location||this._options.followRedirects===!1||statusCode<300||statusCode>=400){response.responseUrl=this._currentUrl,response.redirects=this._redirects,this.emit("response",response),this._requestBodyBuffers=[];return}if(destroyRequest(this._currentRequest),response.destroy(),++this._redirectCount>this._options.maxRedirects)throw new TooManyRedirectsError;var requestHeaders,beforeRedirect=this._options.beforeRedirect;beforeRedirect&&(requestHeaders=Object.assign({Host:response.req.getHeader("host")},this._options.headers));var method=this._options.method;((statusCode===301||statusCode===302)&&this._options.method==="POST"||statusCode===303&&!/^(?:GET|HEAD)$/.test(this._options.method))&&(this._options.method="GET",this._requestBodyBuffers=[],removeMatchingHeaders(/^content-/i,this._options.headers));var currentHostHeader=removeMatchingHeaders(/^host$/i,this._options.headers),currentUrlParts=parseUrl2(this._currentUrl),currentHost=currentHostHeader||currentUrlParts.host,currentUrl=/^\w+:/.test(location)?this._currentUrl:url4.format(Object.assign(currentUrlParts,{host:currentHost})),redirectUrl=resolveUrl(location,currentUrl);if(debug("redirecting to",redirectUrl.href),this._isRedirect=!0,spreadUrlObject(redirectUrl,this._options),(redirectUrl.protocol!==currentUrlParts.protocol&&redirectUrl.protocol!=="https:"||redirectUrl.host!==currentHost&&!isSubdomain(redirectUrl.host,currentHost))&&removeMatchingHeaders(this._headerFilter,this._options.headers),isFunction(beforeRedirect)){var responseDetails={headers:response.headers,statusCode},requestDetails={url:currentUrl,method,headers:requestHeaders};beforeRedirect(this._options,responseDetails,requestDetails),this._sanitizeOptions(this._options)}this._performRequest()};function wrap(protocols){var exports2={maxRedirects:21,maxBodyLength:10485760},nativeProtocols={};return Object.keys(protocols).forEach(function(scheme){var protocol=scheme+":",nativeProtocol=nativeProtocols[protocol]=protocols[scheme],wrappedProtocol=exports2[scheme]=Object.create(nativeProtocol);function request(input,options,callback){return isURL2(input)?input=spreadUrlObject(input):isString(input)?input=spreadUrlObject(parseUrl2(input)):(callback=options,options=validateUrl(input),input={protocol}),isFunction(options)&&(callback=options,options=null),options=Object.assign({maxRedirects:exports2.maxRedirects,maxBodyLength:exports2.maxBodyLength},input,options),options.nativeProtocols=nativeProtocols,!isString(options.host)&&!isString(options.hostname)&&(options.hostname="::1"),assert.equal(options.protocol,protocol,"protocol mismatch"),debug("options",options),new RedirectableRequest(options,callback)}function get(input,options,callback){var wrappedRequest=wrappedProtocol.request(input,options,callback);return wrappedRequest.end(),wrappedRequest}Object.defineProperties(wrappedProtocol,{request:{value:request,configurable:!0,enumerable:!0,writable:!0},get:{value:get,configurable:!0,enumerable:!0,writable:!0}})}),exports2}function noop(){}function parseUrl2(input){var parsed;if(useNativeURL)parsed=new URL3(input);else if(parsed=validateUrl(url4.parse(input)),!isString(parsed.protocol))throw new InvalidUrlError({input});return parsed}function resolveUrl(relative3,base){return useNativeURL?new URL3(relative3,base):parseUrl2(url4.resolve(base,relative3))}function validateUrl(input){if(/^\[/.test(input.hostname)&&!/^\[[:0-9a-f]+\]$/i.test(input.hostname))throw new InvalidUrlError({input:input.href||input});if(/^\[/.test(input.host)&&!/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host))throw new InvalidUrlError({input:input.href||input});return input}function spreadUrlObject(urlObject,target){var spread=target||{};for(var key of preservedUrlFields)spread[key]=urlObject[key];return spread.hostname.startsWith("[")&&(spread.hostname=spread.hostname.slice(1,-1)),spread.port!==""&&(spread.port=Number(spread.port)),spread.path=spread.search?spread.pathname+spread.search:spread.pathname,spread}function removeMatchingHeaders(regex,headers){var lastValue;for(var header in headers)regex.test(header)&&(lastValue=headers[header],delete headers[header]);return lastValue===null||typeof lastValue>"u"?void 0:String(lastValue).trim()}function createErrorType(code,message,baseClass){function CustomError(properties){isFunction(Error.captureStackTrace)&&Error.captureStackTrace(this,this.constructor),Object.assign(this,properties||{}),this.code=code,this.message=this.cause?message+": "+this.cause.message:message}return CustomError.prototype=new(baseClass||Error),Object.defineProperties(CustomError.prototype,{constructor:{value:CustomError,enumerable:!1},name:{value:"Error ["+code+"]",enumerable:!1}}),CustomError}function destroyRequest(request,error2){for(var event of events)request.removeListener(event,eventHandlers[event]);request.on("error",noop),request.destroy(error2)}function isSubdomain(subdomain,domain){assert(isString(subdomain)&&isString(domain));var dot=subdomain.length-domain.length-1;return dot>0&&subdomain[dot]==="."&&subdomain.endsWith(domain)}function isArray(value){return value instanceof Array}function isString(value){return typeof value=="string"||value instanceof String}function isFunction(value){return typeof value=="function"}function isBuffer(value){return typeof value=="object"&&"length"in value}function isURL2(value){return URL3&&value instanceof URL3}function escapeRegex(regex){return regex.replace(/[\]\\/()*+?.$]/g,"\\$&")}module.exports=wrap({http:http2,https});module.exports.wrap=wrap}});var require_web_incoming=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@4.4.3/node_modules/http-proxy-node16/lib/http-proxy/passes/web-incoming.js"(exports,module){var httpNative=__require("http"),httpsNative=__require("https"),web_o=require_web_outgoing(),common=require_common(),followRedirects=require_follow_redirects();web_o=Object.keys(web_o).map(function(pass){return web_o[pass]});var nativeAgents={http:httpNative,https:httpsNative};var supportsAbortedEvent=function(){var ver=process.versions.node.split(".").map(Number);return ver[0]<=14||ver[0]===15&&ver[1]<=4}();module.exports={deleteLength:function(req,res,options){(req.method==="DELETE"||req.method==="OPTIONS")&&!req.headers["content-length"]&&(req.headers["content-length"]="0",delete req.headers["transfer-encoding"])},timeout:function(req,res,options){options.timeout&&req.socket.setTimeout(options.timeout)},XHeaders:function(req,res,options){if(options.xfwd){var encrypted=req.isSpdy||common.hasEncryptedConnection(req),values={for:req.connection.remoteAddress||req.socket.remoteAddress,port:common.getPort(req),proto:encrypted?"https":"http"};["for","port","proto"].forEach(function(header){req.headers["x-forwarded-"+header]=(req.headers["x-forwarded-"+header]||"")+(req.headers["x-forwarded-"+header]?",":"")+values[header]}),req.headers["x-forwarded-host"]=req.headers["x-forwarded-host"]||req.headers.host||""}},stream:function(req,res,options,_,server,clb){server.emit("start",req,res,options.target||options.forward);var agents=options.followRedirects?followRedirects:nativeAgents,http2=agents.http,https=agents.https;if(options.forward){var forwardReq=(options.forward.protocol==="https:"?https:http2).request(common.setupOutgoing(options.ssl||{},options,req,"forward")),forwardError=createErrorHandler(forwardReq,options.forward);if(req.on("error",forwardError),forwardReq.on("error",forwardError),(options.buffer||req).pipe(forwardReq),!options.target)return res.end()}var proxyReq=(options.target.protocol==="https:"?https:http2).request(common.setupOutgoing(options.ssl||{},options,req));proxyReq.on("socket",function(socket){server&&!proxyReq.getHeader("expect")&&server.emit("proxyReq",proxyReq,req,res,options)}),options.proxyTimeout&&proxyReq.setTimeout(options.proxyTimeout,function(){proxyReq.abort()}),supportsAbortedEvent?req.on("aborted",function(){proxyReq.abort()}):res.on("close",function(){var aborted=!res.writableFinished;aborted&&proxyReq.abort()});var proxyError=createErrorHandler(proxyReq,options.target);req.on("error",proxyError),proxyReq.on("error",proxyError);function createErrorHandler(proxyReq2,url4){return function(err){if(req.socket.destroyed&&err.code==="ECONNRESET")return server.emit("econnreset",err,req,res,url4),proxyReq2.abort();clb?clb(err,req,res,url4):server.emit("error",err,req,res,url4)}}(options.buffer||req).pipe(proxyReq),proxyReq.on("response",function(proxyRes){if(server&&server.emit("proxyRes",proxyRes,req,res),!res.headersSent&&!options.selfHandleResponse)for(var i=0;i<web_o.length&&!web_o[i](req,res,proxyRes,options);i++);res.finished?server&&server.emit("end",req,res,proxyRes):(proxyRes.on("end",function(){server&&server.emit("end",req,res,proxyRes)}),options.selfHandleResponse||proxyRes.pipe(res))})}}}});var require_ws_incoming=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@4.4.3/node_modules/http-proxy-node16/lib/http-proxy/passes/ws-incoming.js"(exports,module){var http2=__require("http"),https=__require("https"),common=require_common();module.exports={checkMethodAndHeader:function(req,socket){if(req.method!=="GET"||!req.headers.upgrade||req.headers.upgrade.toLowerCase()!=="websocket")return socket.destroy(),!0},XHeaders:function(req,socket,options){if(options.xfwd){var values={for:req.connection.remoteAddress||req.socket.remoteAddress,port:common.getPort(req),proto:common.hasEncryptedConnection(req)?"wss":"ws"};["for","port","proto"].forEach(function(header){req.headers["x-forwarded-"+header]=(req.headers["x-forwarded-"+header]||"")+(req.headers["x-forwarded-"+header]?",":"")+values[header]})}},stream:function(req,socket,options,head,server,clb){var createHttpHeader=function(line,headers){return Object.keys(headers).reduce(function(head2,key){var value=headers[key];if(!Array.isArray(value))return head2.push(key+": "+value),head2;for(var i=0;i<value.length;i++)head2.push(key+": "+value[i]);return head2},[line]).join(`\r
8
8
  `)+`\r
9
9
  \r
10
10
  `};common.setupSocket(socket),head&&head.length&&socket.unshift(head);var proxyReq=(common.isSSL.test(options.target.protocol)?https:http2).request(common.setupOutgoing(options.ssl||{},options,req));return server&&server.emit("proxyReqWs",proxyReq,req,socket,options,head),proxyReq.on("error",onOutgoingError),proxyReq.on("response",function(res){res.upgrade||(socket.write(createHttpHeader("HTTP/"+res.httpVersion+" "+res.statusCode+" "+res.statusMessage,res.headers)),res.pipe(socket))}),proxyReq.on("upgrade",function(proxyRes,proxySocket,proxyHead){proxySocket.on("error",onOutgoingError),proxySocket.on("end",function(){server.emit("close",proxyRes,proxySocket,proxyHead)}),socket.on("error",function(){proxySocket.destroy()}),common.setupSocket(proxySocket),proxyHead&&proxyHead.length&&proxySocket.unshift(proxyHead),socket.write(createHttpHeader("HTTP/1.1 101 Switching Protocols",proxyRes.headers)),proxySocket.pipe(socket).pipe(proxySocket),server.emit("open",proxySocket),server.emit("proxySocket",proxySocket)}),proxyReq.end();function onOutgoingError(err){clb?clb(err,req,socket):server.emit("error",err,req,socket),socket.end()}}}}});var require_http_proxy=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@4.4.3/node_modules/http-proxy-node16/lib/http-proxy/index.js"(exports,module){var httpProxy2=module.exports,extend=Object.assign,parse_url=__require("url").parse,EE3=require_eventemitter3(),http2=__require("http"),https=__require("https"),web=require_web_incoming(),ws=require_ws_incoming();httpProxy2.Server=ProxyServer;function createRightProxy(type){return function(options){return function(req,res){var passes=type==="ws"?this.wsPasses:this.webPasses,args=[].slice.call(arguments),cntr=args.length-1,head,cbl;typeof args[cntr]=="function"&&(cbl=args[cntr],cntr--);var requestOptions=options;if(!(args[cntr]instanceof Buffer)&&args[cntr]!==res&&(requestOptions=extend({},options),extend(requestOptions,args[cntr]),cntr--),args[cntr]instanceof Buffer&&(head=args[cntr]),["target","forward"].forEach(function(e){typeof requestOptions[e]=="string"&&(requestOptions[e]=parse_url(requestOptions[e]))}),!requestOptions.target&&!requestOptions.forward)return this.emit("error",new Error("Must provide a proper URL as target"));for(var i=0;i<passes.length&&!passes[i](req,res,requestOptions,head,this,cbl);i++);}}}httpProxy2.createRightProxy=createRightProxy;function ProxyServer(options){EE3.call(this),options=options||{},options.prependPath=options.prependPath!==!1,this.web=this.proxyRequest=createRightProxy("web")(options),this.ws=this.proxyWebsocketRequest=createRightProxy("ws")(options),this.options=options,this.webPasses=Object.keys(web).map(function(pass){return web[pass]}),this.wsPasses=Object.keys(ws).map(function(pass){return ws[pass]}),this.on("error",this.onError,this)}__require("util").inherits(ProxyServer,EE3);ProxyServer.prototype.onError=function(err){if(this.listeners("error").length===1)throw err};ProxyServer.prototype.listen=function(port,hostname){var self2=this,closure=function(req,res){self2.web(req,res)};return this._server=this.options.ssl?https.createServer(this.options.ssl,closure):http2.createServer(closure),this.options.ws&&this._server.on("upgrade",function(req,socket,head){self2.ws(req,socket,head)}),this._server.listen(port,hostname),this};ProxyServer.prototype.close=function(callback){var self2=this;this._server&&this._server.close(done);function done(){self2._server=null,callback&&callback.apply(null,arguments)}};ProxyServer.prototype.before=function(type,passName,callback){if(type!=="ws"&&type!=="web")throw new Error("type must be `web` or `ws`");var passes=type==="ws"?this.wsPasses:this.webPasses,i=!1;if(passes.forEach(function(v,idx){v.name===passName&&(i=idx)}),i===!1)throw new Error("No such pass");passes.splice(i,0,callback)};ProxyServer.prototype.after=function(type,passName,callback){if(type!=="ws"&&type!=="web")throw new Error("type must be `web` or `ws`");var passes=type==="ws"?this.wsPasses:this.webPasses,i=!1;if(passes.forEach(function(v,idx){v.name===passName&&(i=idx)}),i===!1)throw new Error("No such pass");passes.splice(i++,0,callback)}}});var require_http_proxy2=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@4.4.3/node_modules/http-proxy-node16/lib/http-proxy.js"(exports,module){var ProxyServer=require_http_proxy().Server;function createProxyServer(options){return new ProxyServer(options)}ProxyServer.createProxyServer=createProxyServer;ProxyServer.createServer=createProxyServer;ProxyServer.createProxy=createProxyServer;module.exports=ProxyServer}});var require_http_proxy_node16=__commonJS({"../../node_modules/.pnpm/http-proxy-node16@1.0.6_debug@4.4.3/node_modules/http-proxy-node16/index.js"(exports,module){module.exports=require_http_proxy2()}});var require_urlparser=__commonJS({"../../node_modules/.pnpm/fast-url-parser@1.1.3/node_modules/fast-url-parser/src/urlparser.js"(exports,module){"use strict";function Url(){this._protocol=null,this._href="",this._port=-1,this._query=null,this.auth=null,this.slashes=null,this.host=null,this.hostname=null,this.hash=null,this.search=null,this.pathname=null,this._prependSlash=!1}var querystring=__require("querystring");Url.queryString=querystring;Url.prototype.parse=function(str,parseQueryString2,hostDenotesSlash,disableAutoEscapeChars){if(typeof str!="string")throw new TypeError("Parameter 'url' must be a string, not "+typeof str);for(var start=0,end=str.length-1;str.charCodeAt(start)<=32;)start++;for(;str.charCodeAt(end)<=32;)end--;if(start=this._parseProtocol(str,start,end),this._protocol!=="javascript"){start=this._parseHost(str,start,end,hostDenotesSlash);var proto=this._protocol;!this.hostname&&(this.slashes||proto&&!slashProtocols[proto])&&(this.hostname=this.host="")}if(start<=end){var ch=str.charCodeAt(start);ch===47||ch===92?this._parsePath(str,start,end,disableAutoEscapeChars):ch===63?this._parseQuery(str,start,end,disableAutoEscapeChars):ch===35?this._parseHash(str,start,end,disableAutoEscapeChars):this._protocol!=="javascript"?this._parsePath(str,start,end,disableAutoEscapeChars):this.pathname=str.slice(start,end+1)}if(!this.pathname&&this.hostname&&this._slashProtocols[this._protocol]&&(this.pathname="/"),parseQueryString2){var search=this.search;search==null&&(search=this.search=""),search.charCodeAt(0)===63&&(search=search.slice(1)),this.query=Url.queryString.parse(search)}};Url.prototype.resolve=function(relative3){return this.resolveObject(Url.parse(relative3,!1,!0)).format()};Url.prototype.format=function(){var auth=this.auth||"";auth&&(auth=encodeURIComponent(auth),auth=auth.replace(/%3A/i,":"),auth+="@");var protocol=this.protocol||"",pathname=this.pathname||"",hash=this.hash||"",search=this.search||"",query="",hostname=this.hostname||"",port=this.port||"",host=!1,scheme="",q=this.query;if(q&&typeof q=="object"&&(query=Url.queryString.stringify(q)),search||(search=query?"?"+query:""),protocol&&protocol.charCodeAt(protocol.length-1)!==58&&(protocol+=":"),this.host)host=auth+this.host;else if(hostname){var ip6=hostname.indexOf(":")>-1;ip6&&(hostname="["+hostname+"]"),host=auth+hostname+(port?":"+port:"")}var slashes=this.slashes||(!protocol||slashProtocols[protocol])&&host!==!1;return protocol?scheme=protocol+(slashes?"//":""):slashes&&(scheme="//"),slashes&&pathname&&pathname.charCodeAt(0)!==47&&(pathname="/"+pathname),search&&search.charCodeAt(0)!==63&&(search="?"+search),hash&&hash.charCodeAt(0)!==35&&(hash="#"+hash),pathname=escapePathName(pathname),search=escapeSearch(search),scheme+(host===!1?"":host)+pathname+search+hash};Url.prototype.resolveObject=function(relative3){typeof relative3=="string"&&(relative3=Url.parse(relative3,!1,!0));var result=this._clone();if(result.hash=relative3.hash,!relative3.href)return result._href="",result;if(relative3.slashes&&!relative3._protocol)return relative3._copyPropsTo(result,!0),slashProtocols[result._protocol]&&result.hostname&&!result.pathname&&(result.pathname="/"),result._href="",result;if(relative3._protocol&&relative3._protocol!==result._protocol){if(!slashProtocols[relative3._protocol])return relative3._copyPropsTo(result,!1),result._href="",result;if(result._protocol=relative3._protocol,!relative3.host&&relative3._protocol!=="javascript"){for(var relPath=(relative3.pathname||"").split("/");relPath.length&&!(relative3.host=relPath.shift()););relative3.host||(relative3.host=""),relative3.hostname||(relative3.hostname=""),relPath[0]!==""&&relPath.unshift(""),relPath.length<2&&relPath.unshift(""),result.pathname=relPath.join("/")}else result.pathname=relative3.pathname;return result.search=relative3.search,result.host=relative3.host||"",result.auth=relative3.auth,result.hostname=relative3.hostname||relative3.host,result._port=relative3._port,result.slashes=result.slashes||relative3.slashes,result._href="",result}var isSourceAbs=result.pathname&&result.pathname.charCodeAt(0)===47,isRelAbs=relative3.host||relative3.pathname&&relative3.pathname.charCodeAt(0)===47,mustEndAbs=isRelAbs||isSourceAbs||result.host&&relative3.pathname,removeAllDots=mustEndAbs,srcPath=result.pathname&&result.pathname.split("/")||[],relPath=relative3.pathname&&relative3.pathname.split("/")||[],psychotic=result._protocol&&!slashProtocols[result._protocol];if(psychotic&&(result.hostname="",result._port=-1,result.host&&(srcPath[0]===""?srcPath[0]=result.host:srcPath.unshift(result.host)),result.host="",relative3._protocol&&(relative3.hostname="",relative3._port=-1,relative3.host&&(relPath[0]===""?relPath[0]=relative3.host:relPath.unshift(relative3.host)),relative3.host=""),mustEndAbs=mustEndAbs&&(relPath[0]===""||srcPath[0]==="")),isRelAbs)result.host=relative3.host?relative3.host:result.host,result.hostname=relative3.hostname?relative3.hostname:result.hostname,result.search=relative3.search,srcPath=relPath;else if(relPath.length)srcPath||(srcPath=[]),srcPath.pop(),srcPath=srcPath.concat(relPath),result.search=relative3.search;else if(relative3.search){if(psychotic){result.hostname=result.host=srcPath.shift();var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):!1;authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return result.search=relative3.search,result._href="",result}if(!srcPath.length)return result.pathname=null,result._href="",result;for(var last=srcPath.slice(-1)[0],hasTrailingSlash=(result.host||relative3.host)&&(last==="."||last==="..")||last==="",up=0,i2=srcPath.length;i2>=0;i2--)last=srcPath[i2],last==="."?srcPath.splice(i2,1):last===".."?(srcPath.splice(i2,1),up++):up&&(srcPath.splice(i2,1),up--);if(!mustEndAbs&&!removeAllDots)for(;up--;up)srcPath.unshift("..");mustEndAbs&&srcPath[0]!==""&&(!srcPath[0]||srcPath[0].charCodeAt(0)!==47)&&srcPath.unshift(""),hasTrailingSlash&&srcPath.join("/").substr(-1)!=="/"&&srcPath.push("");var isAbsolute3=srcPath[0]===""||srcPath[0]&&srcPath[0].charCodeAt(0)===47;if(psychotic){result.hostname=result.host=isAbsolute3?"":srcPath.length?srcPath.shift():"";var authInHost=result.host&&result.host.indexOf("@")>0?result.host.split("@"):!1;authInHost&&(result.auth=authInHost.shift(),result.host=result.hostname=authInHost.shift())}return mustEndAbs=mustEndAbs||result.host&&srcPath.length,mustEndAbs&&!isAbsolute3&&srcPath.unshift(""),result.pathname=srcPath.length===0?null:srcPath.join("/"),result.auth=relative3.auth||result.auth,result.slashes=result.slashes||relative3.slashes,result._href="",result};var punycode=__require("punycode");Url.prototype._hostIdna=function(hostname){return punycode.toASCII(hostname)};var escapePathName=Url.prototype._escapePathName=function(pathname){return containsCharacter2(pathname,35,63)?_escapePath(pathname):pathname},escapeSearch=Url.prototype._escapeSearch=function(search){return containsCharacter2(search,35,-1)?_escapeSearch(search):search};Url.prototype._parseProtocol=function(str,start,end){for(var doLowerCase=!1,protocolCharacters=this._protocolCharacters,i2=start;i2<=end;++i2){var ch=str.charCodeAt(i2);if(ch===58){var protocol=str.slice(start,i2);return doLowerCase&&(protocol=protocol.toLowerCase()),this._protocol=protocol,i2+1}else if(protocolCharacters[ch]===1)ch<97&&(doLowerCase=!0);else return start}return start};Url.prototype._parseAuth=function(str,start,end,decode){var auth=str.slice(start,end+1);decode&&(auth=decodeURIComponent(auth)),this.auth=auth};Url.prototype._parsePort=function(str,start,end){for(var port=0,hadChars=!1,validPort=!0,i2=start;i2<=end;++i2){var ch=str.charCodeAt(i2);if(48<=ch&&ch<=57)port=10*port+(ch-48),hadChars=!0;else{validPort=!1,(ch===92||ch===47)&&(validPort=!0);break}}return port===0&&!hadChars||!validPort?(validPort||(this._port=-2),0):(this._port=port,i2-start)};Url.prototype._parseHost=function(str,start,end,slashesDenoteHost){var hostEndingCharacters=this._hostEndingCharacters,first=str.charCodeAt(start),second=str.charCodeAt(start+1);if((first===47||first===92)&&(second===47||second===92)){if(this.slashes=!0,start===0){if(end<2)return start;var hasAuth=containsCharacter(str,64,2,hostEndingCharacters);if(!hasAuth&&!slashesDenoteHost)return this.slashes=null,start}start+=2}else if(!this._protocol||slashProtocols[this._protocol])return start;for(var doLowerCase=!1,idna=!1,hostNameStart=start,hostNameEnd=end,lastCh=-1,portLength=0,charsAfterDot=0,authNeedsDecoding=!1,j=-1,i2=start;i2<=end;++i2){var ch=str.charCodeAt(i2);if(ch===64)j=i2;else if(ch===37)authNeedsDecoding=!0;else if(hostEndingCharacters[ch]===1)break}if(j>-1&&(this._parseAuth(str,start,j-1,authNeedsDecoding),start=hostNameStart=j+1),str.charCodeAt(start)===91){for(var i2=start+1;i2<=end;++i2){var ch=str.charCodeAt(i2);if(ch===93){str.charCodeAt(i2+1)===58&&(portLength=this._parsePort(str,i2+2,end)+1);var hostname=str.slice(start+1,i2).toLowerCase();return this.hostname=hostname,this.host=this._port>0?"["+hostname+"]:"+this._port:"["+hostname+"]",this.pathname="/",i2+portLength+1}}return start}for(var i2=start;i2<=end;++i2){if(charsAfterDot>62)return this.hostname=this.host=str.slice(start,i2),i2;var ch=str.charCodeAt(i2);if(ch===58){portLength=this._parsePort(str,i2+1,end)+1,hostNameEnd=i2-1;break}else if(ch<97){if(ch===46)charsAfterDot=-1;else if(65<=ch&&ch<=90)doLowerCase=!0;else if(!(ch===45||ch===95||ch===43||48<=ch&&ch<=57)){hostEndingCharacters[ch]===0&&this._noPrependSlashHostEnders[ch]===0&&(this._prependSlash=!0),hostNameEnd=i2-1;break}}else if(ch>=123){if(ch<=126){this._noPrependSlashHostEnders[ch]===0&&(this._prependSlash=!0),hostNameEnd=i2-1;break}idna=!0}lastCh=ch,charsAfterDot++}if(hostNameEnd+1!==start&&hostNameEnd-hostNameStart<=256){var hostname=str.slice(hostNameStart,hostNameEnd+1);doLowerCase&&(hostname=hostname.toLowerCase()),idna&&(hostname=this._hostIdna(hostname)),this.hostname=hostname,this.host=this._port>0?hostname+":"+this._port:hostname}return hostNameEnd+1+portLength};Url.prototype._copyPropsTo=function(input,noProtocol){noProtocol||(input._protocol=this._protocol),input._href=this._href,input._port=this._port,input._prependSlash=this._prependSlash,input.auth=this.auth,input.slashes=this.slashes,input.host=this.host,input.hostname=this.hostname,input.hash=this.hash,input.search=this.search,input.pathname=this.pathname};Url.prototype._clone=function(){var ret=new Url;return ret._protocol=this._protocol,ret._href=this._href,ret._port=this._port,ret._prependSlash=this._prependSlash,ret.auth=this.auth,ret.slashes=this.slashes,ret.host=this.host,ret.hostname=this.hostname,ret.hash=this.hash,ret.search=this.search,ret.pathname=this.pathname,ret};Url.prototype._getComponentEscaped=function(str,start,end,isAfterQuery){for(var cur=start,i2=start,ret="",autoEscapeMap2=isAfterQuery?this._afterQueryAutoEscapeMap:this._autoEscapeMap;i2<=end;++i2){var ch=str.charCodeAt(i2),escaped=autoEscapeMap2[ch];escaped!==""&&escaped!==void 0&&(cur<i2&&(ret+=str.slice(cur,i2)),ret+=escaped,cur=i2+1)}return cur<i2+1&&(ret+=str.slice(cur,i2)),ret};Url.prototype._parsePath=function(str,start,end,disableAutoEscapeChars){for(var pathStart=start,pathEnd=end,escape2=!1,autoEscapeCharacters=this._autoEscapeCharacters,prePath=this._port===-2?"/:":"",i2=start;i2<=end;++i2){var ch=str.charCodeAt(i2);if(ch===35){this._parseHash(str,i2,end,disableAutoEscapeChars),pathEnd=i2-1;break}else if(ch===63){this._parseQuery(str,i2,end,disableAutoEscapeChars),pathEnd=i2-1;break}else!disableAutoEscapeChars&&!escape2&&autoEscapeCharacters[ch]===1&&(escape2=!0)}if(pathStart>pathEnd){this.pathname=prePath===""?"/":prePath;return}var path6;escape2?path6=this._getComponentEscaped(str,pathStart,pathEnd,!1):path6=str.slice(pathStart,pathEnd+1),this.pathname=prePath===""?this._prependSlash?"/"+path6:path6:prePath+path6};Url.prototype._parseQuery=function(str,start,end,disableAutoEscapeChars){for(var queryStart=start,queryEnd=end,escape2=!1,autoEscapeCharacters=this._autoEscapeCharacters,i2=start;i2<=end;++i2){var ch=str.charCodeAt(i2);if(ch===35){this._parseHash(str,i2,end,disableAutoEscapeChars),queryEnd=i2-1;break}else!disableAutoEscapeChars&&!escape2&&autoEscapeCharacters[ch]===1&&(escape2=!0)}if(queryStart>queryEnd){this.search="";return}var query;escape2?query=this._getComponentEscaped(str,queryStart,queryEnd,!0):query=str.slice(queryStart,queryEnd+1),this.search=query};Url.prototype._parseHash=function(str,start,end,disableAutoEscapeChars){if(start>end){this.hash="";return}this.hash=disableAutoEscapeChars?str.slice(start,end+1):this._getComponentEscaped(str,start,end,!0)};Object.defineProperty(Url.prototype,"port",{get:function(){return this._port>=0?""+this._port:null},set:function(v){v==null?this._port=-1:this._port=parseInt(v,10)}});Object.defineProperty(Url.prototype,"query",{get:function(){var query=this._query;if(query!=null)return query;var search=this.search;return search&&(search.charCodeAt(0)===63&&(search=search.slice(1)),search!=="")&&(this._query=search),search},set:function(v){this._query=v}});Object.defineProperty(Url.prototype,"path",{get:function(){var p=this.pathname||"",s=this.search||"";return p||s?p+s:p==null&&s?"/"+s:null},set:function(){}});Object.defineProperty(Url.prototype,"protocol",{get:function(){var proto=this._protocol;return proto&&proto+":"},set:function(v){if(typeof v=="string"){var end=v.length-1;v.charCodeAt(end)===58?this._protocol=v.slice(0,end):this._protocol=v}else v==null&&(this._protocol=null)}});Object.defineProperty(Url.prototype,"href",{get:function(){var href=this._href;return href||(href=this._href=this.format()),href},set:function(v){this._href=v}});Url.parse=function(str,parseQueryString2,hostDenotesSlash,disableAutoEscapeChars){if(str instanceof Url)return str;var ret=new Url;return ret.parse(str,!!parseQueryString2,!!hostDenotesSlash,!!disableAutoEscapeChars),ret};Url.format=function(obj){return typeof obj=="string"&&(obj=Url.parse(obj)),obj instanceof Url?obj.format():Url.prototype.format.call(obj)};Url.resolve=function(source,relative3){return Url.parse(source,!1,!0).resolve(relative3)};Url.resolveObject=function(source,relative3){return source?Url.parse(source,!1,!0).resolveObject(relative3):relative3};function _escapePath(pathname){return pathname.replace(/[?#]/g,function(match){return encodeURIComponent(match)})}function _escapeSearch(search){return search.replace(/#/g,function(match){return encodeURIComponent(match)})}function containsCharacter(string,char1,fromIndex,stopCharacterTable){for(var len2=string.length,i2=fromIndex;i2<len2;++i2){var ch=string.charCodeAt(i2);if(ch===char1)return!0;if(stopCharacterTable[ch]===1)return!1}return!1}function containsCharacter2(string,char1,char2){for(var i2=0,len2=string.length;i2<len2;++i2){var ch=string.charCodeAt(i2);if(ch===char1||ch===char2)return!0}return!1}function makeAsciiTable(spec){var ret=new Uint8Array(128);return spec.forEach(function(item){if(typeof item=="number")ret[item]=1;else for(var start=item[0],end=item[1],j=start;j<=end;++j)ret[j]=1}),ret}var autoEscape=["<",">",'"',"`"," ","\r",`
@@ -33,7 +33,7 @@ ${partHeaders}\r
33
33
  `)))}parts.push(Uint8Array.from(Buffer.from(`--${boundary}--\r
34
34
  `)));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}}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);for(let name of HOP_BY_HOP_REQUEST_HEADERS)middlewareReqHeaders.delete(name);let 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_utils2.isSpawnError)(err)&&err.code==="ENOENT"&&(err.message=`Command not found: ${import_chalk2.default.cyan(err.path,...err.spawnargs)}
35
35
  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)}}if(callLevel===0&&this.orchestrator){let pathname=url3.parse(prevUrl||"/").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)}}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_utils2.isSpawnError)(err)&&err.code==="ENOENT"&&(err.message=`Command not found: ${import_chalk2.default.cyan(err.path,...err.spawnargs)}
36
- 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,dirname2(asset.fsPath),{headers:[{source:"**/*",headers:[{key:"Content-Type",value:asset.contentType||getMimeType(assetKey)}]}]});case"FileBlob":let headers2={"Content-Length":asset.data.length,"Content-Type":asset.contentType||getMimeType(assetKey)};applyResponseTransforms(headers2,responseTransforms??[]),this.setResponseHeaders(res,requestId,headers2),res.end(asset.data);return;case"Lambda":if(!asset.fn){await this.sendError(req,res,requestId,"INTERNAL_LAMBDA_NOT_FOUND");return}requestId=generateRequestId(this.podId,!0);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search}),applyRequestTransforms(req,requestTransforms);let path6=req.url||"/",body=await(0,import_raw_body2.default)(req);debug(`Invoking lambda: "${assetKey}" with ${path6}`);let result;try{result=await this.invokeBuiltLambda(asset,req,requestId,body)}catch(err){console.error(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}statusCode||(res.statusCode=result.statusCode);let lambdaHeaders=result.headers??{};applyResponseTransforms(lambdaHeaders,responseTransforms??[]),this.setResponseHeaders(res,requestId,lambdaHeaders);let resBody;return result.encoding==="base64"&&typeof result.body=="string"?resBody=Buffer.from(result.body,"base64"):resBody=result.body,res.end(resBody);default:await this.sendError(req,res,requestId,"UNKNOWN_ASSET_TYPE")}};if(this.cwd=cwd,this.repoRoot=options.repoRoot??cwd,this.envConfigs={buildEnv:{},runEnv:{},allEnv:{}},this.envValues=options.envValues||{},this.projectId=options.projectId,this.orgId=options.orgId,this.queuePort=options.queuePort,this.runtimeCachePort=options.runtimeCachePort,this.schedulesPort=options.schedulesPort,this.routing=options.routing??!0,this.devCommandPort=options.devCommandPort,this.onConfig=options.onConfig,!this.routing&&!this.devCommandPort)throw new Error("Running without the router needs a `devCommandPort`");this.scheduleBroker=new import_local_schedules2.ScheduleBroker({ownerId:this.orgId??"team_local",projectId:this.projectId??"prj_local",trackId:"development",dispatch:invocation=>this.dispatchSchedule(invocation),onError:(err,invocation)=>{try{output_manager_default.error(`Failed to dispatch schedule "${invocation.schedule.name}": ${(0,import_error_utils2.errorToString)(err)}`)}catch{}}}),this.resourceProxyToken=randomBytes2(32).toString("base64url"),this.reportError=createErrorReporter2(code=>options.onErrorCode?.(code)),this.files={},this.originalProjectSettings=options.projectSettings,this.projectSettings=options.projectSettings,this.services=options.services,this.useImplicitServicesEnvInjection=options.useImplicitServicesEnvInjection??!0,this.caseSensitive=!1,this.apiDir=null,this.apiExtensions=new Set,this.proxy=import_http_proxy_node16.default.createProxyServer({changeOrigin:!0,ws:!0,xfwd:!0}),this.proxy.on("proxyReqWs",(proxyReq,_req,socket)=>{socket.once("close",()=>proxyReq.destroy())}),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_utils2.errorToString)(err)}`),!!res){if("destroy"in res&&typeof res.destroy=="function"){res.destroy();return}res instanceof http.ServerResponse&&(res.headersSent||res.writeHead(502),res.end())}}),this.server=http.createServer(this.devServerHandler),this.server.timeout=0,this.queueServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.queueOrigin,this.handleQueuesRoute)}),this.runtimeCacheServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.runtimeCacheOrigin,this.handleRuntimeCacheRoute)}),this.schedulesServer=http.createServer((req,res)=>{this.schedulesSession&&res.setHeader(LOCAL_SCHEDULES_SESSION_HEADER,this.schedulesSession.session.id),this.handleResourceServerRequest(req,res,this.schedulesOrigin,this.handleSchedulesRoute)}),this.stopping=!1,this.buildMatches=new Map,this.inProgressBuilds=new Map,this.devCacheDir=join4(getVercelDirectory(cwd),"cache"),this.vercelConfigWarning=!1,this.getVercelConfigPromise=null,this.blockingBuildsPromise=null,this.startPromise=null,this.bulkRedirects=null,this.bulkRedirectsSignature=null,this.bulkRedirectsLastPath=null,this.bulkRedirectsResolvedPath=null,this.bulkRedirectsDirty=!0,this.watchAggregationId=null,this.watchAggregationEvents=[],this.watchAggregationTimeout=500,this.filter=path6=>!!path6,this.podId=Math.random().toString(32).slice(-5),this.shutdownCallbacks=new Map}get address(){if(!this._address)throw dev.DEV_INTERNAL_ADDRESS_UNAVAILABLE();return this._address}shouldUseServicesOrchestrator(){return!!(this.services&&this.services.length>0)}hasSubscribers(){return!!this.sidecars?.length}getDevQueueEnv(){return this.queueOrigin?getDevQueueEnv(this.queueOrigin,this.hasSubscribers()):{}}getDevRuntimeCacheEnv(env){return!this.runtimeCacheOrigin||env.RUNTIME_CACHE_ENDPOINT?{}:process.env.RUNTIME_CACHE_ENDPOINT?{RUNTIME_CACHE_ENDPOINT:process.env.RUNTIME_CACHE_ENDPOINT,...process.env.RUNTIME_CACHE_HEADERS?{RUNTIME_CACHE_HEADERS:process.env.RUNTIME_CACHE_HEADERS}:{}}:getDevRuntimeCacheEnv(this.runtimeCacheOrigin,DEV_RUNTIME_CACHE_API_PREFIX)}get resourceEndpoints(){if(!this.queueOrigin||!this.runtimeCacheOrigin)throw new Error("Local resource servers have not started");let proxied=(direct,path6)=>this.routing?`${this.address.origin}${path6}`:direct,runtimeCache=`${this.runtimeCacheOrigin}${DEV_RUNTIME_CACHE_API_PREFIX}`;return{queues:{direct:this.queueOrigin,proxy:proxied(this.queueOrigin,`${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`)},runtimeCache:{direct:runtimeCache,proxy:proxied(runtimeCache,`${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}${DEV_RUNTIME_CACHE_API_PREFIX}`)},...this.schedulesOrigin?{schedules:{direct:this.schedulesOrigin,proxy:proxied(this.schedulesOrigin,`${DEV_SCHEDULES_PROXY_PREFIX}/${this.resourceProxyToken}`)}}:{}}}getDevResourceMeta(){return{devResourceEndpoints:this.resourceEndpoints}}handleResourceServerRequest(req,res,origin,handler){if(!origin||!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}if(!isValidDevResourceHost(origin,req.headers.host)){res.writeHead(403),res.end("Forbidden");return}let pathname=new URL2(req.url||"/","http://127.0.0.1").pathname;handler(req,res,pathname).catch(err=>{output_manager_default.debug(`Local resource request failed for ${req.url||"/"}: ${(0,import_error_utils2.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+sep))&&(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_utils2.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=relative(this.cwd,fsPath);try{await this.getVercelConfig(),this.files[name]=await import_build_utils8.FileFsRef.fromFsPath({fsPath});let extensionless=this.getExtensionlessFile(name);extensionless&&(this.files[extensionless]=await import_build_utils8.FileFsRef.fromFsPath({fsPath})),fileChanged(name,changed,removed),output_manager_default.debug(`File created: ${name}`)}catch(err){if((0,import_error_utils2.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=relative(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=relative(this.cwd,fsPath);try{this.files[name]=await import_build_utils8.FileFsRef.fromFsPath({fsPath}),fileChanged(name,changed,removed),output_manager_default.debug(`File modified: ${name}`)}catch(err){if((0,import_error_utils2.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)}}if(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]))),isInitial){let warnings=new Set;for(let match of this.buildMatches.values()){let{builder}=match.builderWithPkg;if(!builder.getDevWarnings)continue;let builderWarnings=await builder.getDevWarnings({files:this.files,entrypoint:match.entrypoint,workPath:this.cwd,repoRootPath:this.repoRoot,config:{projectSettings:this.projectSettings,...match.config},meta:{isDev:!0,env:this.getBuilderDevEnv(match,this.envConfigs.runEnv),buildEnv:{...this.envConfigs.buildEnv}}});for(let warning of builderWarnings)warnings.add(warning)}for(let warning of warnings)output_manager_default.warn(warning)}}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_utils2.isErrnoException)(err)||err.code!=="ENOENT")throw err}try{return{...this.validateEnvConfig(fileName,base||{},env)}}catch(err){if(err instanceof MissingDotenvVarsError)this.reportError(err),await this.exit();else throw err}return{}}getVercelConfig(){if(this.getVercelConfigPromise)return this.getVercelConfigPromise;this.getVercelConfigPromise=(async()=>{for(;;){let generation=this.configGeneration;try{let config=await this._getVercelConfig();if(this.stopping||generation===this.configGeneration)return config}catch(err){if(this.stopping||generation===this.configGeneration)throw err}this.functionDiscovery=void 0}})();let clear=this.clearVercelConfigPromise;return this.getVercelConfigPromise.then(clear,clear),this.getVercelConfigPromise}get devCommand(){return this.getDevCommand(this.projectSettings)}get devCommandOrigin(){return this.devProcessOrigin}getDevCommand(projectSettings){if(projectSettings?.devCommand)return projectSettings.devCommand;if(projectSettings?.framework){let frameworkSlug=projectSettings.framework,framework=import_frameworks3.frameworkList.find(f=>f.slug===frameworkSlug);if(framework){let defaults=framework.settings.devCommand.value;if(defaults)return defaults}if((0,import_build_utils8.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._address)throw new Error(`Schedule path "${delivery.path}" is not ready because vercel dev is not listening yet`);signal.throwIfAborted();let cronSecret=this.envConfigs.runEnv.CRON_SECRET??process.env.CRON_SECRET,response=await directFetch(`${this._address.origin}${delivery.path}`,{method:delivery.requestMethod,headers:{...delivery.headers,...cronSecret?{authorization:`Bearer ${cronSecret}`}:{}},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 fn=this.getDevFunction(outputPath);if(!fn||this.stopping)return null;if(fn.invocation.type==="http"){if(!this.devProcessOrigin)return null}else if(!this.functionDispatchReady||this.functionReconciliations>0||!this.getDevFunctionMatch(fn))return null;return request=>this.invokeDevFunction(outputPath,request)}getDevFunctionMatch(fn){if(fn.invocation.type!=="entrypoint"||fn.scope.target!=="builder")return;let{entrypoint}=fn.invocation;return[...this.buildMatches.values()].find(match=>match.entrypoint===entrypoint&&match.use===fn.scope.build.use&&(0,import_fast_deep_equal.default)(match.config??{},fn.scope.build.config??{}))}canonicalizeFunctionBuild(match){if(![...this.functionRegistry.functions.values()].some(fn=>this.getDevFunctionMatch(fn)===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 fn=this.getDevFunction(outputPath);if(!fn||!this.resolveDevFunction(outputPath))return null;let generation=this.configGeneration,isCurrent=()=>!this.stopping&&generation===this.configGeneration&&this.getDevFunction(outputPath)===fn;if(fn.invocation.type==="http"){let response=await directFetch(`${this.devProcessOrigin}${fn.invocation.pathname}`,{...request,redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}let match=this.getDevFunctionMatch(fn),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(fn)===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}=fn.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,configPath=localConfigFlagPath();if(!configPath){let{compileVercelConfig}=await import("../../chunks/compile-vercel-config-H5MLKZB5.js"),compiled=await compileVercelConfig(this.cwd);configPath=getLocalPathConfig(this.cwd,!!compiled.sourceFile)}let[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(fn=>fn.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;if(!vercelConfig.experimentalServices&&!hasResolvedServices&&(!vercelConfig.builds||vercelConfig.builds.length===0)){let{projectSettings,cleanUrls,trailingSlash}=vercelConfig,files=(await staticFiles(this.cwd,{})).map(f=>relative(this.cwd,f));sourceFiles=files;let detectionOptions={tag:"latest",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,fn])=>error2.message.startsWith(`The pattern "${pattern}" defined in \`functions\` `)&&fn.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_utils8.isExperimentalServiceV2);this.sidecars=await collectBuilderDevSidecars({builds:this.shouldUseServicesOrchestrator()?services.map(service=>service.builder):vercelConfig.builds??[],workPath:this.cwd,services})}let functionBuilds=[...vercelConfig.builds??[]];Array.isArray(vercelConfig.builds)&&((this.getDevCommand(nextProjectSettings)||hasServices)&&(vercelConfig.builds=vercelConfig.builds.filter(this.shouldBuildInDev)),vercelConfig.builds.sort(sortBuilders)),vercelConfig.routes=(vercelConfig.routes||[]).filter(route=>"has"in route?(this.vercelConfigWarning||(this.vercelConfigWarning=!0,output_manager_default.warn(`The "has" property in ${vercelConfig[import_client.fileNameSymbol]} will be ignored during development. Deployments will work as expected.`)),!1):!0);let[runEnv,buildEnv]=await Promise.all([this.getLocalEnv(".env",vercelConfig.env),this.getLocalEnv(".env.build",vercelConfig.build?.env)]),allEnv={...buildEnv,...runEnv},envFromCloud=Object.keys(allEnv).length===0;if(envFromCloud){let envValues={...this.envValues};this.address.host&&(envValues.VERCEL_URL=this.address.host),allEnv={...envValues},runEnv={...envValues},buildEnv={...envValues}}runEnv.NODE_ENV??=process.env.NODE_ENV??"development",allEnv.NODE_ENV??=runEnv.NODE_ENV,runEnv.NOW_REGION="dev1",buildEnv.NOW_REGION="dev1",allEnv.NOW_REGION="dev1",allEnv.VERCEL_ENV="development",allEnv.VERCEL="1",this.projectId&&!process.env.VERCEL_PROJECT_ID&&("VERCEL_PROJECT_ID"in allEnv||(allEnv.VERCEL_PROJECT_ID=this.projectId),"VERCEL_PROJECT_ID"in runEnv||(runEnv.VERCEL_PROJECT_ID=this.projectId)),this.orgId&&!process.env.VERCEL_ORG_ID&&("VERCEL_ORG_ID"in allEnv||(allEnv.VERCEL_ORG_ID=this.orgId),"VERCEL_ORG_ID"in runEnv||(runEnv.VERCEL_ORG_ID=this.orgId)),nextProjectSettings?.autoExposeSystemEnvs&&(runEnv.VERCEL_REGION="dev1"),runEnv.VERCEL_CLI_VERSION=pkg_default.version,Object.assign(runEnv,this.getDevQueueEnv()),Object.assign(runEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(allEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(runEnv,this.getDevRuntimeCacheEnv(runEnv));let hasQueueFunctions=Object.values(functionConfig.functions??{}).some(fn=>fn.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=>relative(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((0,import_build_utils8.getNamedSchedules)(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(fn=>fn.invocation.type==="http")&&!(0,import_fast_deep_equal.default)(this.devCommandEnv,allEnv)),previousProcess=this.devProcess,previousOrigin=this.devProcessOrigin,previousCommand=this.currentDevCommand,previousEnv=this.devCommandEnv,previousRuntime={projectSettings:this.projectSettings,allEnv:previousEnv??this.envConfigs.allEnv},restarted,validated=!1;try{if(this.initialDevCommandStarted&&await this.runDevCommand(restartForFunctionEnv,{projectSettings:nextProjectSettings,allEnv},origin=>{restarted={origin}}),this.stopping||generation!==this.configGeneration)return vercelConfig;this.queueBroker?.validateFunctionSubscriptions(subscriptions),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&(this.scheduleBroker.validateStatic(staticSchedules),this.scheduleBroker.reconcileStatic(staticSchedules),this.staticSchedulesSnapshot=structuredClone(staticSchedules)),validated=!0}finally{!this.stopping&&!validated&&(this.devProcess!==previousProcess||this.devProcessOrigin!==previousOrigin||this.currentDevCommand!==previousCommand||this.devCommandEnv!==previousEnv)&&await this.runDevCommand(!0,previousRuntime)}this.projectSettings=nextProjectSettings,this.caseSensitive=hasNewRoutingProperties(vercelConfig),this.apiDir=(0,import_fs_detectors2.detectApiDirectory)(vercelConfig.builds||[]),this.apiExtensions=(0,import_fs_detectors2.detectApiExtensions)(vercelConfig.builds||[]),this.envConfigs={buildEnv,runEnv,allEnv},this.envFromCloud=envFromCloud,this.functionRegistry=registry,this.functionConfig=vercelConfig,restarted&&(this.devProcessOrigin=restarted.origin),this.queueBroker?.setFunctionSubscriptions(subscriptions,outputPath=>this.resolveDevFunction(outputPath));for(let pattern of unmatchedPatterns)if(!this.unmatchedQueuePatterns.has(pattern)){let warning=dev.DEV_QUEUE_FUNCTION_UNMATCHED({pattern});output_manager_default.warn(`[${warning.name}] ${warning.message} ${warning.fix}`)}return this.unmatchedQueuePatterns=new Set(unmatchedPatterns),this.onConfig?.(functionConfig),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_utils2.errorToString)(err)}`)}}}async readJsonFile(filePath,strict=!1){let rel,abs;isAbsolute2(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_utils2.isErrnoException)(err)&&err.code==="ENOENT"))throw err;if((0,import_error_utils2.isError)(err))(0,import_error_utils2.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 message=validate(config);message&&(output_manager_default.error(message),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=relative(this.cwd,fsPath);return relativePath===""?!1:!this.filter(relativePath)}start(...listenSpec){return this.startPromise||(this.startPromise=this._start(...listenSpec).catch(async err=>{throw await this.stop(),err})),this.startPromise}async _start(...listenSpec){if(this.stopping)return;if(!import_fs_extra.default.existsSync(this.cwd))throw dev.DEV_CWD_NOT_FOUND({cwd:this.cwd});if(!import_fs_extra.default.lstatSync(this.cwd).isDirectory())throw dev.DEV_CWD_NOT_DIRECTORY({cwd:this.cwd});let{ig}=await(0,import_client.getVercelIgnore)(this.cwd);this.filter=ig.createFilter();let address=this.routing?null:`http://localhost:${this.devCommandPort}`;for(;typeof address!="string";){if(this.stopping)return;try{address=(await(this.listenerStartup=(0,import_async_listen.listen)(this.server,...listenSpec))).toString()}catch(err){if((0,import_error_utils2.isErrnoException)(err))if(output_manager_default.debug(`Got listen error: ${err.code}`),err.code==="EADDRINUSE")typeof listenSpec[0]=="number"?(output_manager_default.note(`Requested port ${import_chalk2.default.yellow(String(listenSpec[0]))} is already in use`),listenSpec[0]++):(this.reportError(dev.DEV_LISTEN_ADDRESS_IN_USE({address:String(listenSpec[0])})),process.exit(1));else throw err;else throw err}}if(this.stopping)return;this._address=new URL2(replaceLocalhost(address)),this.runtimeCache=new RuntimeCacheStore;let devCommandPorts=this.devCommandPort?[this.devCommandPort]:[],runtimeCacheListener=await(this.listenerStartup=listenOnDevResourcePort(this.runtimeCacheServer,{name:"Runtime Cache",flag:"--runtime-cache-port",defaultPort:DEV_RUNTIME_CACHE_DEFAULT_PORT,port:this.runtimeCachePort,reservedPorts:[this.queuePort,this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT,...devCommandPorts].filter(port=>port!==void 0&&port!==0)}));if(this.stopping)return;this.runtimeCacheOrigin=runtimeCacheListener.origin,runtimeCacheListener.defaultPort!==void 0&&output_manager_default.warn(`Runtime Cache default port ${runtimeCacheListener.defaultPort} is unavailable; listening on ${runtimeCacheListener.port} instead.
36
+ 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,dirname2(asset.fsPath),{headers:[{source:"**/*",headers:[{key:"Content-Type",value:asset.contentType||getMimeType(assetKey)}]}]});case"FileBlob":let headers2={"Content-Length":asset.data.length,"Content-Type":asset.contentType||getMimeType(assetKey)};applyResponseTransforms(headers2,responseTransforms??[]),this.setResponseHeaders(res,requestId,headers2),res.end(asset.data);return;case"Lambda":if(!asset.fn){await this.sendError(req,res,requestId,"INTERNAL_LAMBDA_NOT_FOUND");return}requestId=generateRequestId(this.podId,!0);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search}),applyRequestTransforms(req,requestTransforms);let path6=req.url||"/",body=await(0,import_raw_body2.default)(req);debug(`Invoking lambda: "${assetKey}" with ${path6}`);let result;try{result=await this.invokeBuiltLambda(asset,req,requestId,body)}catch(err){console.error(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}statusCode||(res.statusCode=result.statusCode);let lambdaHeaders=result.headers??{};applyResponseTransforms(lambdaHeaders,responseTransforms??[]),this.setResponseHeaders(res,requestId,lambdaHeaders);let resBody;return result.encoding==="base64"&&typeof result.body=="string"?resBody=Buffer.from(result.body,"base64"):resBody=result.body,res.end(resBody);default:await this.sendError(req,res,requestId,"UNKNOWN_ASSET_TYPE")}};if(this.cwd=cwd,this.repoRoot=options.repoRoot??cwd,this.envConfigs={buildEnv:{},runEnv:{},allEnv:{}},this.envValues=options.envValues||{},this.projectId=options.projectId,this.orgId=options.orgId,this.queuePort=options.queuePort,this.runtimeCachePort=options.runtimeCachePort,this.schedulesPort=options.schedulesPort,this.routing=options.routing??!0,this.devCommandPort=options.devCommandPort,this.onConfig=options.onConfig,!this.routing&&!this.devCommandPort)throw new Error("Running without the router needs a `devCommandPort`");this.scheduleBroker=new import_local_schedules2.ScheduleBroker({ownerId:this.orgId??"team_local",projectId:this.projectId??"prj_local",trackId:"development",dispatch:invocation=>this.dispatchSchedule(invocation),onError:(err,invocation)=>{try{output_manager_default.error(`Failed to dispatch schedule "${invocation.schedule.name}": ${(0,import_error_utils2.errorToString)(err)}`)}catch{}}}),this.resourceProxyToken=randomBytes2(32).toString("base64url"),this.reportError=createErrorReporter2(code=>options.onErrorCode?.(code)),this.files={},this.originalProjectSettings=options.projectSettings,this.projectSettings=options.projectSettings,this.services=options.services,this.useImplicitServicesEnvInjection=options.useImplicitServicesEnvInjection??!0,this.caseSensitive=!1,this.apiDir=null,this.apiExtensions=new Set,this.proxy=import_http_proxy_node16.default.createProxyServer({changeOrigin:!0,ws:!0,xfwd:!0}),this.proxy.on("proxyReqWs",(proxyReq,_req,socket)=>{socket.once("close",()=>proxyReq.destroy())}),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_utils2.errorToString)(err)}`),!!res){if("destroy"in res&&typeof res.destroy=="function"){res.destroy();return}res instanceof http.ServerResponse&&(res.headersSent||res.writeHead(502),res.end())}}),this.server=http.createServer(this.devServerHandler),this.server.timeout=0,this.queueServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.queueOrigin,this.handleQueuesRoute)}),this.runtimeCacheServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.runtimeCacheOrigin,this.handleRuntimeCacheRoute)}),this.schedulesServer=http.createServer((req,res)=>{this.schedulesSession&&res.setHeader(LOCAL_SCHEDULES_SESSION_HEADER,this.schedulesSession.session.id),this.handleResourceServerRequest(req,res,this.schedulesOrigin,this.handleSchedulesRoute)}),this.stopping=!1,this.buildMatches=new Map,this.inProgressBuilds=new Map,this.devCacheDir=join4(getVercelDirectory(cwd),"cache"),this.vercelConfigWarning=!1,this.getVercelConfigPromise=null,this.blockingBuildsPromise=null,this.startPromise=null,this.bulkRedirects=null,this.bulkRedirectsSignature=null,this.bulkRedirectsLastPath=null,this.bulkRedirectsResolvedPath=null,this.bulkRedirectsDirty=!0,this.watchAggregationId=null,this.watchAggregationEvents=[],this.watchAggregationTimeout=500,this.filter=path6=>!!path6,this.podId=Math.random().toString(32).slice(-5),this.shutdownCallbacks=new Map}get address(){if(!this._address)throw dev.DEV_INTERNAL_ADDRESS_UNAVAILABLE();return this._address}shouldUseServicesOrchestrator(){return!!(this.services&&this.services.length>0)}hasSubscribers(){return!!this.sidecars?.length}getDevQueueEnv(){return this.queueOrigin?getDevQueueEnv(this.queueOrigin,this.hasSubscribers()):{}}getDevRuntimeCacheEnv(env){return!this.runtimeCacheOrigin||env.RUNTIME_CACHE_ENDPOINT?{}:process.env.RUNTIME_CACHE_ENDPOINT?{RUNTIME_CACHE_ENDPOINT:process.env.RUNTIME_CACHE_ENDPOINT,...process.env.RUNTIME_CACHE_HEADERS?{RUNTIME_CACHE_HEADERS:process.env.RUNTIME_CACHE_HEADERS}:{}}:getDevRuntimeCacheEnv(this.runtimeCacheOrigin,DEV_RUNTIME_CACHE_API_PREFIX)}get resourceEndpoints(){if(!this.queueOrigin||!this.runtimeCacheOrigin)throw new Error("Local resource servers have not started");let proxied=(direct,path6)=>this.routing?`${this.address.origin}${path6}`:direct,runtimeCache=`${this.runtimeCacheOrigin}${DEV_RUNTIME_CACHE_API_PREFIX}`;return{queues:{direct:this.queueOrigin,proxy:proxied(this.queueOrigin,`${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`)},runtimeCache:{direct:runtimeCache,proxy:proxied(runtimeCache,`${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}${DEV_RUNTIME_CACHE_API_PREFIX}`)},...this.schedulesOrigin?{schedules:{direct:this.schedulesOrigin,proxy:proxied(this.schedulesOrigin,`${DEV_SCHEDULES_PROXY_PREFIX}/${this.resourceProxyToken}`)}}:{}}}getDevResourceMeta(){return{devResourceEndpoints:this.resourceEndpoints}}handleResourceServerRequest(req,res,origin,handler){if(!origin||!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}if(!isValidDevResourceHost(origin,req.headers.host)){res.writeHead(403),res.end("Forbidden");return}let pathname=new URL2(req.url||"/","http://127.0.0.1").pathname;handler(req,res,pathname).catch(err=>{output_manager_default.debug(`Local resource request failed for ${req.url||"/"}: ${(0,import_error_utils2.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+sep))&&(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_utils2.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=relative(this.cwd,fsPath);try{await this.getVercelConfig(),this.files[name]=await import_build_utils8.FileFsRef.fromFsPath({fsPath});let extensionless=this.getExtensionlessFile(name);extensionless&&(this.files[extensionless]=await import_build_utils8.FileFsRef.fromFsPath({fsPath})),fileChanged(name,changed,removed),output_manager_default.debug(`File created: ${name}`)}catch(err){if((0,import_error_utils2.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=relative(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=relative(this.cwd,fsPath);try{this.files[name]=await import_build_utils8.FileFsRef.fromFsPath({fsPath}),fileChanged(name,changed,removed),output_manager_default.debug(`File modified: ${name}`)}catch(err){if((0,import_error_utils2.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)}}if(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]))),isInitial){let warnings=new Set;for(let match of this.buildMatches.values()){let{builder}=match.builderWithPkg;if(!builder.getDevWarnings)continue;let builderWarnings=await builder.getDevWarnings({files:this.files,entrypoint:match.entrypoint,workPath:this.cwd,repoRootPath:this.repoRoot,config:{projectSettings:this.projectSettings,...match.config},meta:{isDev:!0,env:this.getBuilderDevEnv(match,this.envConfigs.runEnv),buildEnv:{...this.envConfigs.buildEnv}}});for(let warning of builderWarnings)warnings.add(warning)}for(let warning of warnings)output_manager_default.warn(warning)}}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_utils2.isErrnoException)(err)||err.code!=="ENOENT")throw err}try{return{...this.validateEnvConfig(fileName,base||{},env)}}catch(err){if(err instanceof MissingDotenvVarsError)this.reportError(err),await this.exit();else throw err}return{}}getVercelConfig(){if(this.getVercelConfigPromise)return this.getVercelConfigPromise;this.getVercelConfigPromise=(async()=>{for(;;){let generation=this.configGeneration;try{let config=await this._getVercelConfig();if(this.stopping||generation===this.configGeneration)return config}catch(err){if(this.stopping||generation===this.configGeneration)throw err}this.functionDiscovery=void 0}})();let clear=this.clearVercelConfigPromise;return this.getVercelConfigPromise.then(clear,clear),this.getVercelConfigPromise}get devCommand(){return this.getDevCommand(this.projectSettings)}get devCommandOrigin(){return this.devProcessOrigin}getDevCommand(projectSettings){if(projectSettings?.devCommand)return projectSettings.devCommand;if(projectSettings?.framework){let frameworkSlug=projectSettings.framework,framework=import_frameworks3.frameworkList.find(f=>f.slug===frameworkSlug);if(framework){let defaults=framework.settings.devCommand.value;if(defaults)return defaults}if((0,import_build_utils8.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._address)throw new Error(`Schedule path "${delivery.path}" is not ready because vercel dev is not listening yet`);signal.throwIfAborted();let cronSecret=this.envConfigs.runEnv.CRON_SECRET??process.env.CRON_SECRET,response=await directFetch(`${this._address.origin}${delivery.path}`,{method:delivery.requestMethod,headers:{...delivery.headers,...cronSecret?{authorization:`Bearer ${cronSecret}`}:{}},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 fn=this.getDevFunction(outputPath);if(!fn||this.stopping)return null;if(fn.invocation.type==="http"){if(!this.devProcessOrigin)return null}else if(!this.functionDispatchReady||this.functionReconciliations>0||!this.getDevFunctionMatch(fn))return null;return request=>this.invokeDevFunction(outputPath,request)}getDevFunctionMatch(fn){if(fn.invocation.type!=="entrypoint"||fn.scope.target!=="builder")return;let{entrypoint}=fn.invocation;return[...this.buildMatches.values()].find(match=>match.entrypoint===entrypoint&&match.use===fn.scope.build.use&&(0,import_fast_deep_equal.default)(match.config??{},fn.scope.build.config??{}))}canonicalizeFunctionBuild(match){if(![...this.functionRegistry.functions.values()].some(fn=>this.getDevFunctionMatch(fn)===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 fn=this.getDevFunction(outputPath);if(!fn||!this.resolveDevFunction(outputPath))return null;let generation=this.configGeneration,isCurrent=()=>!this.stopping&&generation===this.configGeneration&&this.getDevFunction(outputPath)===fn;if(fn.invocation.type==="http"){let response=await directFetch(`${this.devProcessOrigin}${fn.invocation.pathname}`,{...request,redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}let match=this.getDevFunctionMatch(fn),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(fn)===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}=fn.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,configPath=localConfigFlagPath();if(!configPath){let{compileVercelConfig}=await import("../../chunks/compile-vercel-config-HAQYXHPB.js"),compiled=await compileVercelConfig(this.cwd);configPath=getLocalPathConfig(this.cwd,!!compiled.sourceFile)}let[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(fn=>fn.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;if(!vercelConfig.experimentalServices&&!hasResolvedServices&&(!vercelConfig.builds||vercelConfig.builds.length===0)){let{projectSettings,cleanUrls,trailingSlash}=vercelConfig,files=(await staticFiles(this.cwd,{})).map(f=>relative(this.cwd,f));sourceFiles=files;let detectionOptions={tag:"latest",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,fn])=>error2.message.startsWith(`The pattern "${pattern}" defined in \`functions\` `)&&fn.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_utils8.isExperimentalServiceV2);this.sidecars=await collectBuilderDevSidecars({builds:this.shouldUseServicesOrchestrator()?services.map(service=>service.builder):vercelConfig.builds??[],workPath:this.cwd,services})}let functionBuilds=[...vercelConfig.builds??[]];Array.isArray(vercelConfig.builds)&&((this.getDevCommand(nextProjectSettings)||hasServices)&&(vercelConfig.builds=vercelConfig.builds.filter(this.shouldBuildInDev)),vercelConfig.builds.sort(sortBuilders)),vercelConfig.routes=(vercelConfig.routes||[]).filter(route=>"has"in route?(this.vercelConfigWarning||(this.vercelConfigWarning=!0,output_manager_default.warn(`The "has" property in ${vercelConfig[import_client.fileNameSymbol]} will be ignored during development. Deployments will work as expected.`)),!1):!0);let[runEnv,buildEnv]=await Promise.all([this.getLocalEnv(".env",vercelConfig.env),this.getLocalEnv(".env.build",vercelConfig.build?.env)]),allEnv={...buildEnv,...runEnv},envFromCloud=Object.keys(allEnv).length===0;if(envFromCloud){let envValues={...this.envValues};this.address.host&&(envValues.VERCEL_URL=this.address.host),allEnv={...envValues},runEnv={...envValues},buildEnv={...envValues}}runEnv.NODE_ENV??=process.env.NODE_ENV??"development",allEnv.NODE_ENV??=runEnv.NODE_ENV,runEnv.NOW_REGION="dev1",buildEnv.NOW_REGION="dev1",allEnv.NOW_REGION="dev1",allEnv.VERCEL_ENV="development",allEnv.VERCEL="1",this.projectId&&!process.env.VERCEL_PROJECT_ID&&("VERCEL_PROJECT_ID"in allEnv||(allEnv.VERCEL_PROJECT_ID=this.projectId),"VERCEL_PROJECT_ID"in runEnv||(runEnv.VERCEL_PROJECT_ID=this.projectId)),this.orgId&&!process.env.VERCEL_ORG_ID&&("VERCEL_ORG_ID"in allEnv||(allEnv.VERCEL_ORG_ID=this.orgId),"VERCEL_ORG_ID"in runEnv||(runEnv.VERCEL_ORG_ID=this.orgId)),nextProjectSettings?.autoExposeSystemEnvs&&(runEnv.VERCEL_REGION="dev1"),runEnv.VERCEL_CLI_VERSION=pkg_default.version,Object.assign(runEnv,this.getDevQueueEnv()),Object.assign(runEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(allEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(runEnv,this.getDevRuntimeCacheEnv(runEnv));let hasQueueFunctions=Object.values(functionConfig.functions??{}).some(fn=>fn.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=>relative(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((0,import_build_utils8.getNamedSchedules)(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(fn=>fn.invocation.type==="http")&&!(0,import_fast_deep_equal.default)(this.devCommandEnv,allEnv)),previousProcess=this.devProcess,previousOrigin=this.devProcessOrigin,previousCommand=this.currentDevCommand,previousEnv=this.devCommandEnv,previousRuntime={projectSettings:this.projectSettings,allEnv:previousEnv??this.envConfigs.allEnv},restarted,validated=!1;try{if(this.initialDevCommandStarted&&await this.runDevCommand(restartForFunctionEnv,{projectSettings:nextProjectSettings,allEnv},origin=>{restarted={origin}}),this.stopping||generation!==this.configGeneration)return vercelConfig;this.queueBroker?.validateFunctionSubscriptions(subscriptions),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&(this.scheduleBroker.validateStatic(staticSchedules),this.scheduleBroker.reconcileStatic(staticSchedules),this.staticSchedulesSnapshot=structuredClone(staticSchedules)),validated=!0}finally{!this.stopping&&!validated&&(this.devProcess!==previousProcess||this.devProcessOrigin!==previousOrigin||this.currentDevCommand!==previousCommand||this.devCommandEnv!==previousEnv)&&await this.runDevCommand(!0,previousRuntime)}this.projectSettings=nextProjectSettings,this.caseSensitive=hasNewRoutingProperties(vercelConfig),this.apiDir=(0,import_fs_detectors2.detectApiDirectory)(vercelConfig.builds||[]),this.apiExtensions=(0,import_fs_detectors2.detectApiExtensions)(vercelConfig.builds||[]),this.envConfigs={buildEnv,runEnv,allEnv},this.envFromCloud=envFromCloud,this.functionRegistry=registry,this.functionConfig=vercelConfig,restarted&&(this.devProcessOrigin=restarted.origin),this.queueBroker?.setFunctionSubscriptions(subscriptions,outputPath=>this.resolveDevFunction(outputPath));for(let pattern of unmatchedPatterns)if(!this.unmatchedQueuePatterns.has(pattern)){let warning=dev.DEV_QUEUE_FUNCTION_UNMATCHED({pattern});output_manager_default.warn(`[${warning.name}] ${warning.message} ${warning.fix}`)}return this.unmatchedQueuePatterns=new Set(unmatchedPatterns),this.onConfig?.(functionConfig),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_utils2.errorToString)(err)}`)}}}async readJsonFile(filePath,strict=!1){let rel,abs;isAbsolute2(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_utils2.isErrnoException)(err)&&err.code==="ENOENT"))throw err;if((0,import_error_utils2.isError)(err))(0,import_error_utils2.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 message=validate(config);message&&(output_manager_default.error(message),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=relative(this.cwd,fsPath);return relativePath===""?!1:!this.filter(relativePath)}start(...listenSpec){return this.startPromise||(this.startPromise=this._start(...listenSpec).catch(async err=>{throw await this.stop(),err})),this.startPromise}async _start(...listenSpec){if(this.stopping)return;if(!import_fs_extra.default.existsSync(this.cwd))throw dev.DEV_CWD_NOT_FOUND({cwd:this.cwd});if(!import_fs_extra.default.lstatSync(this.cwd).isDirectory())throw dev.DEV_CWD_NOT_DIRECTORY({cwd:this.cwd});let{ig}=await(0,import_client.getVercelIgnore)(this.cwd);this.filter=ig.createFilter();let address=this.routing?null:`http://localhost:${this.devCommandPort}`;for(;typeof address!="string";){if(this.stopping)return;try{address=(await(this.listenerStartup=(0,import_async_listen.listen)(this.server,...listenSpec))).toString()}catch(err){if((0,import_error_utils2.isErrnoException)(err))if(output_manager_default.debug(`Got listen error: ${err.code}`),err.code==="EADDRINUSE")typeof listenSpec[0]=="number"?(output_manager_default.note(`Requested port ${import_chalk2.default.yellow(String(listenSpec[0]))} is already in use`),listenSpec[0]++):(this.reportError(dev.DEV_LISTEN_ADDRESS_IN_USE({address:String(listenSpec[0])})),process.exit(1));else throw err;else throw err}}if(this.stopping)return;this._address=new URL2(replaceLocalhost(address)),this.runtimeCache=new RuntimeCacheStore;let devCommandPorts=this.devCommandPort?[this.devCommandPort]:[],runtimeCacheListener=await(this.listenerStartup=listenOnDevResourcePort(this.runtimeCacheServer,{name:"Runtime Cache",flag:"--runtime-cache-port",defaultPort:DEV_RUNTIME_CACHE_DEFAULT_PORT,port:this.runtimeCachePort,reservedPorts:[this.queuePort,this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT,...devCommandPorts].filter(port=>port!==void 0&&port!==0)}));if(this.stopping)return;this.runtimeCacheOrigin=runtimeCacheListener.origin,runtimeCacheListener.defaultPort!==void 0&&output_manager_default.warn(`Runtime Cache default port ${runtimeCacheListener.defaultPort} is unavailable; listening on ${runtimeCacheListener.port} instead.
37
37
  External clients configured for ${runtimeCacheListener.defaultPort} will not reach this dev server. Pin a port with --runtime-cache-port.`);let queueListener=await(this.listenerStartup=listenOnDevResourcePort(this.queueServer,{name:"Vercel Queues",flag:"--queue-port",defaultPort:DEV_QUEUE_DEFAULT_PORT,port:this.queuePort,reservedPorts:[this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT,...devCommandPorts]}));if(this.stopping)return;this.queueOrigin=queueListener.origin,queueListener.defaultPort!==void 0&&output_manager_default.warn(`Vercel Queues default port ${queueListener.defaultPort} is unavailable; listening on ${queueListener.port} instead.
38
38
  External clients configured for ${queueListener.defaultPort} will not reach this dev server. Pin a port with --queue-port.`),this.queueBroker=new QueueBroker([],name=>this.orchestrator?.getServiceOrigin(name)??this.sidecarOrchestrator?.getServiceOrigin(name)??null);let schedulesListener=await(this.listenerStartup=listenOnDevResourcePort(this.schedulesServer,{name:"Vercel Schedules",flag:"--schedules-port",defaultPort:DEV_SCHEDULES_DEFAULT_PORT,port:this.schedulesPort,reservedPorts:devCommandPorts}));if(this.stopping||(this.schedulesOrigin=schedulesListener.origin,this.schedulesSessionPublication=createLocalSchedulesSession(this.cwd,`http://127.0.0.1:${schedulesListener.port}`,this.projectId??"prj_local").then(async published=>{this.stopping?await published.dispose():this.schedulesSession=published}),await this.schedulesSessionPublication,this.stopping))return;schedulesListener.defaultPort!==void 0&&output_manager_default.print(import_chalk2.default.yellow(`! Vercel Schedules default port ${schedulesListener.defaultPort} is unavailable; listening on ${schedulesListener.port} instead.
39
39
  Pin a port with --schedules-port for clients outside the dev server.