vercel 64.5.0 → 64.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/{add-KBBLLPHW.js → add-J6YV6RJ7.js} +1 -1
- package/dist/chunks/{add-CG73LA5A.js → add-LN5C4Y2G.js} +1 -1
- package/dist/chunks/add-UBG7IGYE.js +8 -0
- package/dist/chunks/{build-7EWHBKAN.js → build-7QUO5T72.js} +1 -1
- package/dist/chunks/chunk-2B2Z447M.js +10 -0
- package/dist/chunks/{chunk-XEBMH33W.js → chunk-2EYJFHEL.js} +1 -1
- package/dist/chunks/chunk-2IRZ2C5L.js +9 -0
- package/dist/chunks/{chunk-UGMTKOTN.js → chunk-2LMIOQID.js} +1 -1
- package/dist/chunks/{chunk-TCQZFIBR.js → chunk-2PSLXHNT.js} +1 -1
- package/dist/chunks/chunk-3BTEMYLT.js +7 -0
- package/dist/chunks/chunk-4ITTBUCW.js +7 -0
- package/dist/chunks/chunk-4KYSK2MS.js +7 -0
- package/dist/chunks/{chunk-XXCWQPAH.js → chunk-4XKEOH4J.js} +1 -1
- package/dist/chunks/{chunk-VS7O22ED.js → chunk-54KLVDB5.js} +1 -1
- package/dist/chunks/{chunk-MPZFMEVK.js → chunk-7ENWK2AH.js} +1 -1
- package/dist/chunks/{chunk-QOFK5PKB.js → chunk-A4NHFQVX.js} +2 -2
- package/dist/chunks/{chunk-QEXSF4NA.js → chunk-AAFST44A.js} +1 -1
- package/dist/chunks/chunk-AGH2CMUM.js +7 -0
- package/dist/chunks/chunk-ANUSL4ES.js +7 -0
- package/dist/chunks/chunk-AOYNYH5D.js +7 -0
- package/dist/chunks/chunk-BMQREWR6.js +10 -0
- package/dist/chunks/chunk-BXHADCSX.js +7 -0
- package/dist/chunks/{chunk-Q5ZGA2RO.js → chunk-CFEJIJGS.js} +1 -1
- package/dist/chunks/{chunk-7GFRZWLE.js → chunk-CQQQSUQX.js} +1 -1
- package/dist/chunks/{chunk-JH257EDL.js → chunk-D7X7W4F4.js} +1 -1
- package/dist/chunks/{chunk-UQIVF4Q2.js → chunk-DD5XIW5T.js} +1 -1
- package/dist/chunks/{chunk-ZQKDO5PL.js → chunk-DQLWDDNU.js} +1 -1
- package/dist/chunks/{chunk-PAOR4MQZ.js → chunk-DX6PPIY7.js} +1 -1
- package/dist/chunks/chunk-EU2FGSLR.js +15 -0
- package/dist/chunks/{chunk-6UCSM3CZ.js → chunk-EVEH3L3V.js} +1 -1
- package/dist/chunks/{chunk-TPVAPVQC.js → chunk-EVXOSCYR.js} +1 -1
- package/dist/chunks/chunk-EWK3VAME.js +9 -0
- package/dist/chunks/{chunk-DRXOTZSJ.js → chunk-EWUSBHX5.js} +1 -1
- package/dist/chunks/chunk-F2TLISI5.js +7 -0
- package/dist/chunks/chunk-FOGLMAZE.js +7 -0
- package/dist/chunks/{chunk-3DP66SQ4.js → chunk-FZUNGPGO.js} +1 -1
- package/dist/chunks/{chunk-GVUB6QGX.js → chunk-GH6O7YJ3.js} +1 -1
- package/dist/chunks/{chunk-6QRT6USI.js → chunk-GOVZY7W2.js} +1 -1
- package/dist/chunks/{chunk-LD5U73LA.js → chunk-HGTMU34S.js} +1 -1
- package/dist/chunks/{chunk-ZZ3LJ22B.js → chunk-HJV7CTD4.js} +2 -2
- package/dist/chunks/{chunk-OHVPJNGY.js → chunk-I7KMJTOY.js} +1 -1
- package/dist/chunks/{chunk-PTI3TP7P.js → chunk-IULNLFPX.js} +1 -1
- package/dist/chunks/{chunk-JZ7FDBS4.js → chunk-JHB3TYKZ.js} +1 -1
- package/dist/chunks/{chunk-H3KYG32S.js → chunk-JJSDTLBW.js} +1 -1
- package/dist/chunks/{chunk-V3RDOM3U.js → chunk-JSCK6WWR.js} +3 -3
- package/dist/chunks/chunk-JXKKJ5OI.js +7 -0
- package/dist/chunks/{chunk-DXLLC7ZM.js → chunk-KJKM2UNP.js} +1 -1
- package/dist/chunks/chunk-KJWOXBZV.js +7 -0
- package/dist/chunks/chunk-KYMABVTF.js +25 -0
- package/dist/chunks/{chunk-2UPVIVAA.js → chunk-M2NKATEC.js} +1 -1
- package/dist/chunks/{chunk-TE2EE7DR.js → chunk-MGOPTP7N.js} +1 -1
- package/dist/chunks/{chunk-5S2NK6K6.js → chunk-MP27ZZFO.js} +1 -1
- package/dist/chunks/{chunk-3GUO6F6P.js → chunk-N5SAC4AS.js} +1 -1
- package/dist/chunks/{chunk-LUJL3KFT.js → chunk-N7YVHGLM.js} +1 -1
- package/dist/chunks/{chunk-GWB27IAS.js → chunk-NBNZYZFM.js} +1 -1
- package/dist/chunks/chunk-O3AL3QFA.js +7 -0
- package/dist/chunks/chunk-O5ZJ5YJP.js +10 -0
- package/dist/chunks/{chunk-3NNH2U5M.js → chunk-OGH32TS2.js} +1 -1
- package/dist/chunks/chunk-OS62YRSW.js +7 -0
- package/dist/chunks/{chunk-VRAMXFRB.js → chunk-P4U47GXI.js} +4 -3
- package/dist/chunks/{chunk-5NXYYFRL.js → chunk-PA5N7YTJ.js} +1 -1
- package/dist/chunks/{chunk-TKBORMUF.js → chunk-PADL3C6Z.js} +1 -1
- package/dist/chunks/chunk-PE5BSEYV.js +7 -0
- package/dist/chunks/{chunk-CITTRAYH.js → chunk-PNR5J6ZW.js} +1 -1
- package/dist/chunks/chunk-PPWMHBWP.js +9 -0
- package/dist/chunks/chunk-PUKYAALC.js +7 -0
- package/dist/chunks/{chunk-5AYB3JRL.js → chunk-QQ6IA4O5.js} +1 -1
- package/dist/chunks/{chunk-BJXMXDBM.js → chunk-QRCJKCMF.js} +1 -1
- package/dist/chunks/{chunk-SI7FQJIE.js → chunk-QW4W2UB6.js} +1 -1
- package/dist/chunks/{chunk-LYU4MVL5.js → chunk-R5QHLEAJ.js} +4 -4
- package/dist/chunks/chunk-R6Y4Z5VL.js +7 -0
- package/dist/chunks/{chunk-JIGCN5QS.js → chunk-RD7VCVW5.js} +3 -3
- package/dist/chunks/chunk-S76ILVQO.js +7 -0
- package/dist/chunks/chunk-SADXKDBI.js +7 -0
- package/dist/chunks/{chunk-HARXQZV3.js → chunk-SCJH3KSQ.js} +1 -1
- package/dist/chunks/{chunk-7QQIWMAT.js → chunk-SQXVQT2O.js} +5 -5
- package/dist/chunks/{chunk-CMEEAXVV.js → chunk-TD7MFXUO.js} +1 -1
- package/dist/chunks/{chunk-2UMWTCY7.js → chunk-TVHFWIH4.js} +1 -1
- package/dist/chunks/{chunk-GLH4PVMY.js → chunk-UI53O6MW.js} +1 -1
- package/dist/chunks/chunk-VO6FF6DY.js +7 -0
- package/dist/chunks/chunk-WFJEWVTE.js +12 -0
- package/dist/chunks/{chunk-OUHPDA7Q.js → chunk-WKZ6JSGZ.js} +1 -1
- package/dist/chunks/{chunk-OYMFOCD5.js → chunk-WX2KXEZV.js} +1 -1
- package/dist/chunks/{chunk-YQKURZ5W.js → chunk-X44OEPBR.js} +1 -1
- package/dist/chunks/{chunk-P5BNAP5T.js → chunk-X5HOJBDL.js} +7 -7
- package/dist/chunks/{chunk-ACVDKHVS.js → chunk-XGO6AXX5.js} +2 -2
- package/dist/chunks/chunk-Y4GLHDBA.js +9 -0
- package/dist/chunks/{chunk-WN7EJWN4.js → chunk-YE6WQYJH.js} +2 -2
- package/dist/chunks/chunk-Z5NJL63U.js +7 -0
- package/dist/chunks/chunk-ZOYMKZOR.js +7 -0
- package/dist/chunks/{chunk-TLEBLYBS.js → chunk-ZT2HVX54.js} +1 -1
- package/dist/chunks/{clear-35NUHHDI.js → clear-HKGEIG6F.js} +1 -1
- package/dist/chunks/{compile-vercel-config-UQIYIVA6.js → compile-vercel-config-ZY34MDLE.js} +1 -1
- package/dist/chunks/{config-FZD3R5VT.js → config-33ZMAOLB.js} +1 -1
- package/dist/chunks/config-VWDIXJZA.js +7 -0
- package/dist/chunks/config-validator.mjs +1 -1
- package/dist/chunks/{constants-ICJL2EO5.js → constants-JAB7MRSK.js} +1 -1
- package/dist/chunks/delete-OMER3AX3.js +10 -0
- package/dist/chunks/{delete-6LSSOF4X.js → delete-ZHGL7GGN.js} +1 -1
- package/dist/chunks/{detect-projects-THLTMO7V.js → detect-projects-PNODS4M7.js} +1 -1
- package/dist/chunks/{detect-services-GFVD2C3W.js → detect-services-ABFXK5B7.js} +1 -1
- package/dist/chunks/disable-OIGHKAMI.js +7 -0
- package/dist/chunks/discard-XUMTJVVB.js +14 -0
- package/dist/chunks/edit-3DIEWIVC.js +8 -0
- package/dist/chunks/{edit-R2RUDKC4.js → edit-IQ74VVWW.js} +1 -1
- package/dist/chunks/enable-AVCTKWMV.js +7 -0
- package/dist/chunks/{export-KTLACTAJ.js → export-LS4WTCAJ.js} +1 -1
- package/dist/chunks/future-BSDI3CNY.js +7 -0
- package/dist/chunks/generate-cert-for-deploy-FEZT4VSA.js +7 -0
- package/dist/chunks/image-BIOIWB4M.js +7 -0
- package/dist/chunks/{import-builders-JONKAYLL.js → import-builders-5TVTITKF.js} +1 -1
- package/dist/chunks/inspect-2OWYT5HO.js +13 -0
- package/dist/chunks/{inspect-JDSFHP6X.js → inspect-4OQTNJ46.js} +1 -1
- package/dist/chunks/{inspect-7IZ7M2TX.js → inspect-FR333BCC.js} +1 -1
- package/dist/chunks/{inspect-PQNECP2Z.js → inspect-VEBZWYJL.js} +1 -1
- package/dist/chunks/{inspect-PWLUWUGV.js → inspect-WPYSJNEK.js} +1 -1
- package/dist/chunks/list-LZCBVTIL.js +12 -0
- package/dist/chunks/{list-3N2CBVOG.js → list-Z43SODYP.js} +1 -1
- package/dist/chunks/{list-2G2BWD4T.js → list-ZK7VDRVT.js} +2 -2
- package/dist/chunks/{login-LLM3Q6GJ.js → login-36BXMMDQ.js} +1 -1
- package/dist/chunks/login-HAND2C3L.js +7 -0
- package/dist/chunks/logs-JYROMZI7.js +7 -0
- package/dist/chunks/{ls-5YLXAARZ.js → ls-H3ICVEYT.js} +1 -1
- package/dist/chunks/ls-IMAHWKOH.js +8 -0
- package/dist/chunks/ls-LYVIYO4J.js +12 -0
- package/dist/chunks/ls-M7YO74RP.js +12 -0
- package/dist/chunks/ls-QND7WBWE.js +12 -0
- package/dist/chunks/ls-VWA57ZVD.js +12 -0
- package/dist/chunks/ls-YWZLCIGC.js +11 -0
- package/dist/chunks/mutate-JQF3GLZP.js +9 -0
- package/dist/chunks/notifications-2SS4R53X.js +7 -0
- package/dist/chunks/open-RF3GYOHD.js +7 -0
- package/dist/chunks/openapi-GTAWN7OT.js +7 -0
- package/dist/chunks/permissions-G4F4PLFB.js +7 -0
- package/dist/chunks/prompt-missing-credentials-CV5NLAYI.js +7 -0
- package/dist/chunks/publish-KXUGNXEK.js +15 -0
- package/dist/chunks/pull-ELQ3GVJJ.js +7 -0
- package/dist/chunks/purchase-domain-if-available-QDQJOGOX.js +7 -0
- package/dist/chunks/{push-6LE54BCC.js → push-WSYAQQKI.js} +1 -1
- package/dist/chunks/query-ESQIFSJ6.js +12 -0
- package/dist/chunks/reauthenticate-H7ZY6BVA.js +7 -0
- package/dist/chunks/reorder-SADHAXS4.js +10 -0
- package/dist/chunks/{reply-6HUIX4AX.js → reply-UFH3BEMN.js} +1 -1
- package/dist/chunks/{resolve-TNBNGA3G.js → resolve-5THDM4PN.js} +1 -1
- package/dist/chunks/resolve-agent-team-MCTKBED5.js +7 -0
- package/dist/chunks/restore-3ZTRYEOV.js +16 -0
- package/dist/chunks/rm-GUSBRP6P.js +8 -0
- package/dist/chunks/rm-HUQFQOP2.js +8 -0
- package/dist/chunks/rm-WVA4E2BL.js +8 -0
- package/dist/chunks/rm-ZL4VR3BA.js +8 -0
- package/dist/chunks/rm-ZQWP6MUB.js +8 -0
- package/dist/chunks/routes-ZOLO53UC.js +7 -0
- package/dist/chunks/rule-inspect-WJ6ENOME.js +8 -0
- package/dist/chunks/{schema-HIKNWMV2.js → schema-7ACGW22H.js} +1 -1
- package/dist/chunks/{schema-QHZO72DB.js → schema-D2CWSXZU.js} +7 -7
- package/dist/chunks/{select-org-CK5CWC3A.js → select-org-3BWXFGPH.js} +1 -1
- package/dist/chunks/set-5I5CPDY3.js +7 -0
- package/dist/chunks/setup-and-link-HJSR6ANM.js +7 -0
- package/dist/chunks/skills-C2WOCF5Q.js +590 -0
- package/dist/chunks/{tags-35DFWGDC.js → tags-HTY22QMH.js} +1 -1
- package/dist/chunks/{types-77UW6BI4.js → types-6PREOZWK.js} +1 -1
- package/dist/chunks/update-6TDKMDKO.js +8 -0
- package/dist/commands/build/index.js +3 -3
- package/dist/commands/deploy/index.js +12 -9
- package/dist/commands/dev/index.js +3 -3
- package/dist/commands/env/index.js +13 -13
- package/dist/commands/link/index.js +1 -1
- package/dist/commands/list/index.js +2 -2
- package/dist/commands-bulk.js +315 -275
- package/dist/help.js +1 -1
- package/dist/index.js +2 -2
- package/dist/internal-build.js +1 -1
- package/dist/root-help-commands.mjs +1 -1
- package/dist/runtime-assets/dev-tunnel/api/tunnel.ts +443 -0
- package/dist/runtime-assets/dev-tunnel/lib/env.ts +25 -0
- package/dist/runtime-assets/dev-tunnel/lib/tunnel_pb.ts +505 -0
- package/dist/version.mjs +1 -1
- package/package.json +63 -57
- package/dist/chunks/add-U5U56FJR.js +0 -8
- package/dist/chunks/chunk-2B3A3MOX.js +0 -7
- package/dist/chunks/chunk-74QCXPNW.js +0 -7
- package/dist/chunks/chunk-7NNENHGN.js +0 -7
- package/dist/chunks/chunk-BFRDBBSO.js +0 -7
- package/dist/chunks/chunk-CMKLX4DC.js +0 -7
- package/dist/chunks/chunk-D4MW3RDW.js +0 -7
- package/dist/chunks/chunk-DDLM6CIQ.js +0 -10
- package/dist/chunks/chunk-GVVIFYQE.js +0 -7
- package/dist/chunks/chunk-HJRAWEA2.js +0 -7
- package/dist/chunks/chunk-ILFUNCJZ.js +0 -7
- package/dist/chunks/chunk-ITKS32PG.js +0 -7
- package/dist/chunks/chunk-J6O6JW2K.js +0 -7
- package/dist/chunks/chunk-KUGXOLL7.js +0 -25
- package/dist/chunks/chunk-MI7W4QMV.js +0 -7
- package/dist/chunks/chunk-MYHJNSCW.js +0 -15
- package/dist/chunks/chunk-N2TNA2FE.js +0 -9
- package/dist/chunks/chunk-U73RXMGU.js +0 -7
- package/dist/chunks/chunk-UCAE5Z5L.js +0 -7
- package/dist/chunks/chunk-VEMJINMZ.js +0 -13
- package/dist/chunks/chunk-VLDU2MDL.js +0 -7
- package/dist/chunks/chunk-VRWLNWNE.js +0 -7
- package/dist/chunks/chunk-W3TGCMRW.js +0 -9
- package/dist/chunks/chunk-WCBNKVVG.js +0 -9
- package/dist/chunks/chunk-Y24OSBXP.js +0 -7
- package/dist/chunks/chunk-ZBDLYNUF.js +0 -7
- package/dist/chunks/chunk-ZDKSDWSO.js +0 -9
- package/dist/chunks/chunk-ZMY3GQBK.js +0 -7
- package/dist/chunks/config-IQE5C7PZ.js +0 -7
- package/dist/chunks/delete-IBRCB3S3.js +0 -10
- package/dist/chunks/disable-4TODXYTB.js +0 -7
- package/dist/chunks/discard-WHC5FKWF.js +0 -14
- package/dist/chunks/edit-3DXOWQMF.js +0 -8
- package/dist/chunks/enable-2OAHPKCN.js +0 -7
- package/dist/chunks/future-JZ3RVO4B.js +0 -7
- package/dist/chunks/generate-cert-for-deploy-D4IHTKQS.js +0 -7
- package/dist/chunks/image-UW5U6CRJ.js +0 -7
- package/dist/chunks/inspect-2FS4PYBH.js +0 -13
- package/dist/chunks/list-Y3OA4KFK.js +0 -11
- package/dist/chunks/login-VQN3F7JU.js +0 -7
- package/dist/chunks/logs-XEJPLFXM.js +0 -7
- package/dist/chunks/ls-2DACOWSU.js +0 -12
- package/dist/chunks/ls-2M7QSW2F.js +0 -12
- package/dist/chunks/ls-7DJWHOK4.js +0 -12
- package/dist/chunks/ls-GY2YLYMD.js +0 -12
- package/dist/chunks/ls-NJEJSYSO.js +0 -11
- package/dist/chunks/ls-OAJKYQEL.js +0 -8
- package/dist/chunks/mutate-G2I4ISF4.js +0 -9
- package/dist/chunks/notifications-6MXYY2V6.js +0 -7
- package/dist/chunks/open-YKOYB7PH.js +0 -7
- package/dist/chunks/openapi-36GMGEXR.js +0 -7
- package/dist/chunks/permissions-RRP6IEHS.js +0 -7
- package/dist/chunks/prompt-missing-credentials-WQUF6X6K.js +0 -7
- package/dist/chunks/publish-AQ3FYC3J.js +0 -15
- package/dist/chunks/pull-HT2MQ3ML.js +0 -7
- package/dist/chunks/purchase-domain-if-available-NDEUZYHK.js +0 -7
- package/dist/chunks/query-SNY42BTX.js +0 -12
- package/dist/chunks/reauthenticate-4SGT475I.js +0 -7
- package/dist/chunks/reorder-SRF3NE5U.js +0 -10
- package/dist/chunks/resolve-agent-team-XSXRT42F.js +0 -7
- package/dist/chunks/restore-HK4SWMZP.js +0 -16
- package/dist/chunks/rm-4VXZ3AIX.js +0 -8
- package/dist/chunks/rm-ESSU4MS4.js +0 -8
- package/dist/chunks/rm-EWPYZXTX.js +0 -8
- package/dist/chunks/rm-GNDGYUKQ.js +0 -8
- package/dist/chunks/rm-SKCAZTYN.js +0 -8
- package/dist/chunks/routes-LK2HUGAK.js +0 -7
- package/dist/chunks/rule-inspect-RHHD5UIR.js +0 -8
- package/dist/chunks/rules-FF5FU7BV.js +0 -7
- package/dist/chunks/set-5P44OPZP.js +0 -7
- package/dist/chunks/setup-and-link-OLSKD2HE.js +0 -7
- package/dist/chunks/update-WHBFIV22.js +0 -8
|
@@ -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-VRAMXFRB.js";import{loadVercelConfig,tryDetectServices}from"../../chunks/chunk-5NXYYFRL.js";import"../../chunks/chunk-BJXMXDBM.js";import{FIX_BY_CODE,createErrorReporter,import_write_build_result,require_detect_builders_with_services,require_get_files,require_mime_types,require_schedule_entrypoint,require_service_schedules,toDiagnostic}from"../../chunks/chunk-JH257EDL.js";import{importBuilders,require_npa}from"../../chunks/chunk-PAOR4MQZ.js";import"../../chunks/chunk-4CACOKMS.js";import"../../chunks/chunk-COD3WAUI.js";import{LOCAL_SCHEDULES_SESSION_HEADER,createLocalSchedulesSession}from"../../chunks/chunk-SF4E3AQ3.js";import"../../chunks/chunk-GVUB6QGX.js";import"../../chunks/chunk-QHJLRTVY.js";import{require_fast_deep_equal}from"../../chunks/chunk-MCRKBVZA.js";import{getUpdateCommand}from"../../chunks/chunk-U73RXMGU.js";import{readJSONFile}from"../../chunks/chunk-3DP66SQ4.js";import"../../chunks/chunk-OHVPJNGY.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-MPZFMEVK.js";import{validateConfig}from"../../chunks/chunk-QEXSF4NA.js";import"../../chunks/chunk-IQ7FPAI4.js";import"../../chunks/chunk-MZ3QGJH3.js";import"../../chunks/chunk-EAUDC24V.js";import{pickOverrides}from"../../chunks/chunk-OYMFOCD5.js";import{require_dist as require_dist5}from"../../chunks/chunk-WN7EJWN4.js";import{require_brace_expansion,require_dist as require_dist3,require_dist2 as require_dist4,require_minimatch}from"../../chunks/chunk-5S2NK6K6.js";import{require_main}from"../../chunks/chunk-JZ7FDBS4.js";import"../../chunks/chunk-RRDNKB2X.js";import"../../chunks/chunk-MVGTMPMI.js";import"../../chunks/chunk-SACGQMVQ.js";import"../../chunks/chunk-BPUANOGW.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-P2O5DOYE.js";import{require_raw_body}from"../../chunks/chunk-XOETL6DB.js";import"../../chunks/chunk-KKCBFBJK.js";import{VERCEL_OIDC_TOKEN}from"../../chunks/chunk-SI7FQJIE.js";import"../../chunks/chunk-DRXOTZSJ.js";import{require_json_parse_better_errors}from"../../chunks/chunk-25565AGS.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-J24BABG4.js";import{pullEnvRecords}from"../../chunks/chunk-ZMY3GQBK.js";import{printProjectNotFoundError}from"../../chunks/chunk-VEMJINMZ.js";import"../../chunks/chunk-CITTRAYH.js";import"../../chunks/chunk-PVASGBEF.js";import{require_frameworks}from"../../chunks/chunk-MVCAUS4F.js";import{DEV_QUEUE_API_PREFIX,DEV_QUEUE_DEFAULT_PORT,DEV_QUEUE_PROXY_PREFIX,DEV_RESOURCE_TOKEN,DEV_RUNTIME_CACHE_DEFAULT_PORT,DEV_SCHEDULES_DEFAULT_PORT,DEV_SCHEDULES_PROXY_PREFIX,devCommand,getDevQueueEnv,getDevSchedulesEnv,isValidDevResourceHost,listenOnDevResourcePort}from"../../chunks/chunk-TPVAPVQC.js";import{require_dist as require_dist2}from"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-CMKLX4DC.js";import"../../chunks/chunk-EVQJ7SCV.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-WYI4VNXT.js";import"../../chunks/chunk-2B3A3MOX.js";import"../../chunks/chunk-IVIZLWZQ.js";import"../../chunks/chunk-HVUJNVPS.js";import{help}from"../../chunks/chunk-H3KYG32S.js";import"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-HARXQZV3.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{detectExplicitScope,getLocalPathConfig,highlight}from"../../chunks/chunk-GLH4PVMY.js";import{TelemetryClient}from"../../chunks/chunk-KUGXOLL7.js";import{getGlobalPathConfig}from"../../chunks/chunk-XEBMH33W.js";import"../../chunks/chunk-VKXEOL4K.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{isNativeBinaryInstall}from"../../chunks/chunk-NWGBDBZI.js";import"../../chunks/chunk-4SAVH3H7.js";import"../../chunks/chunk-ZS2WS4AM.js";import"../../chunks/chunk-AOWWC6WZ.js";import{directFetch}from"../../chunks/chunk-MY4MONOH.js";import{parseArguments}from"../../chunks/chunk-VLDU2MDL.js";import{buildCommandWithYes,outputActionRequired}from"../../chunks/chunk-DDLM6CIQ.js";import{getFlagsSpecification}from"../../chunks/chunk-MI7W4QMV.js";import{VERCEL_DIR,findRepoRoot,getLinkedProject,getVercelDirectory,require_lib,require_pluralize,resolveProjectCwd}from"../../chunks/chunk-JIGCN5QS.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import{printAlignedLabel}from"../../chunks/chunk-IJCCFLCQ.js";import"../../chunks/chunk-ZQME5XUJ.js";import"../../chunks/chunk-2VBFQZ72.js";import{CantParseJSONFile,LambdaSizeExceededError,MissingDotenvVarsError,NowError,require_bytes}from"../../chunks/chunk-XSDAUM4F.js";import{cmd,getCommandName,getCommandNamePlain,getTitleName}from"../../chunks/chunk-JESNVRVR.js";import{Diagnostic,defineDiagnostics,init_dist,link_default,output_manager_default,require_build_utils}from"../../chunks/chunk-M774HRX5.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import{pkg_default}from"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import{require_supports_color}from"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__commonJS,__require,__toESM}from"../../chunks/chunk-BZENIQ7N.js";var require_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@3.1.0/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@3.1.0/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_ms2=__commonJS({"../../node_modules/.pnpm/ms@2.0.0/node_modules/ms/index.js"(exports,module){var s=1e3,m=s*60,h=m*60,d=h*24,y=d*365.25;module.exports=function(val,options){options=options||{};var type=typeof val;if(type==="string"&&val.length>0)return parse2(val);if(type==="number"&&isNaN(val)===!1)return options.long?fmtLong(val):fmtShort(val);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(val))};function parse2(str){if(str=String(str),!(str.length>100)){var match=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);if(match){var n=parseFloat(match[1]),type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(ms9){return ms9>=d?Math.round(ms9/d)+"d":ms9>=h?Math.round(ms9/h)+"h":ms9>=m?Math.round(ms9/m)+"m":ms9>=s?Math.round(ms9/s)+"s":ms9+"ms"}function fmtLong(ms9){return plural3(ms9,d,"day")||plural3(ms9,h,"hour")||plural3(ms9,m,"minute")||plural3(ms9,s,"second")||ms9+" ms"}function plural3(ms9,n,name){if(!(ms9<n))return ms9<n*1.5?Math.floor(ms9/n)+" "+name:Math.ceil(ms9/n)+" "+name+"s"}}});var require_debug=__commonJS({"../../node_modules/.pnpm/debug@3.1.0/node_modules/debug/src/debug.js"(exports,module){exports=module.exports=createDebug.debug=createDebug.default=createDebug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require_ms2();exports.instances=[];exports.names=[];exports.skips=[];exports.formatters={};function selectColor(namespace){var hash=0,i;for(i in namespace)hash=(hash<<5)-hash+namespace.charCodeAt(i),hash|=0;return exports.colors[Math.abs(hash)%exports.colors.length]}function createDebug(namespace){var prevTime;function debug(){if(debug.enabled){var self2=debug,curr=+new Date,ms9=curr-(prevTime||curr);self2.diff=ms9,self2.prev=prevTime,self2.curr=curr,prevTime=curr;for(var args=new Array(arguments.length),i=0;i<args.length;i++)args[i]=arguments[i];args[0]=exports.coerce(args[0]),typeof args[0]!="string"&&args.unshift("%O");var index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,function(match,format){if(match==="%%")return match;index++;var formatter=exports.formatters[format];if(typeof formatter=="function"){var val=args[index];match=formatter.call(self2,val),args.splice(index,1),index--}return match}),exports.formatArgs.call(self2,args);var logFn=debug.log||exports.log||console.log.bind(console);logFn.apply(self2,args)}}return debug.namespace=namespace,debug.enabled=exports.enabled(namespace),debug.useColors=exports.useColors(),debug.color=selectColor(namespace),debug.destroy=destroy,typeof exports.init=="function"&&exports.init(debug),exports.instances.push(debug),debug}function destroy(){var index=exports.instances.indexOf(this);return index!==-1?(exports.instances.splice(index,1),!0):!1}function enable(namespaces){exports.save(namespaces),exports.names=[],exports.skips=[];var i,split=(typeof namespaces=="string"?namespaces:"").split(/[\s,]+/),len=split.length;for(i=0;i<len;i++)split[i]&&(namespaces=split[i].replace(/\*/g,".*?"),namespaces[0]==="-"?exports.skips.push(new RegExp("^"+namespaces.substr(1)+"$")):exports.names.push(new RegExp("^"+namespaces+"$")));for(i=0;i<exports.instances.length;i++){var instance=exports.instances[i];instance.enabled=exports.enabled(instance.namespace)}}function disable(){exports.enable("")}function enabled(name){if(name[name.length-1]==="*")return!0;var i,len;for(i=0,len=exports.skips.length;i<len;i++)if(exports.skips[i].test(name))return!1;for(i=0,len=exports.names.length;i<len;i++)if(exports.names[i].test(name))return!0;return!1}function coerce(val){return val instanceof Error?val.stack||val.message:val}}});var require_browser=__commonJS({"../../node_modules/.pnpm/debug@3.1.0/node_modules/debug/src/browser.js"(exports,module){exports=module.exports=require_debug();exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage=typeof chrome<"u"&&typeof chrome.storage<"u"?chrome.storage.local:localstorage();exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){return typeof window<"u"&&window.process&&window.process.type==="renderer"?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}exports.formatters.j=function(v){try{return JSON.stringify(v)}catch(err){return"[UnexpectedJSONParseError]: "+err.message}};function formatArgs(args){var useColors2=this.useColors;if(args[0]=(useColors2?"%c":"")+this.namespace+(useColors2?" %c":" ")+args[0]+(useColors2?"%c ":" ")+"+"+exports.humanize(this.diff),!!useColors2){var c="color: "+this.color;args.splice(1,0,c,"color: inherit");var index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,function(match){match!=="%%"&&(index++,match==="%c"&&(lastC=index))}),args.splice(lastC,0,c)}}function log(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{namespaces==null?exports.storage.removeItem("debug"):exports.storage.debug=namespaces}catch{}}function load(){var r;try{r=exports.storage.debug}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}exports.enable(load());function localstorage(){try{return window.localStorage}catch{}}}});var require_node=__commonJS({"../../node_modules/.pnpm/debug@3.1.0/node_modules/debug/src/node.js"(exports,module){var tty=__require("tty"),util=__require("util");exports=module.exports=require_debug();exports.init=init;exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.colors=[6,2,3,4,5,1];try{supportsColor=require_supports_color(),supportsColor&&supportsColor.level>=2&&(exports.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}var supportsColor;exports.inspectOpts=Object.keys(process.env).filter(function(key){return/^debug_/i.test(key)}).reduce(function(obj,key){var prop=key.substring(6).toLowerCase().replace(/_([a-z])/g,function(_,k){return k.toUpperCase()}),val=process.env[key];return/^(yes|on|true|enabled)$/i.test(val)?val=!0:/^(no|off|false|disabled)$/i.test(val)?val=!1:val==="null"?val=null:val=Number(val),obj[prop]=val,obj},{});function useColors(){return"colors"in exports.inspectOpts?!!exports.inspectOpts.colors:tty.isatty(process.stderr.fd)}exports.formatters.o=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts).split(`
|
|
7
|
+
import{displayDetectedServices,readConfig,setupAndLink}from"../../chunks/chunk-P4U47GXI.js";import{loadVercelConfig,tryDetectServices}from"../../chunks/chunk-PA5N7YTJ.js";import"../../chunks/chunk-QRCJKCMF.js";import{FIX_BY_CODE,createErrorReporter,import_write_build_result,require_detect_builders_with_services,require_get_files,require_mime_types,require_schedule_entrypoint,require_service_schedules,toDiagnostic}from"../../chunks/chunk-D7X7W4F4.js";import{importBuilders,require_npa}from"../../chunks/chunk-DX6PPIY7.js";import"../../chunks/chunk-4CACOKMS.js";import"../../chunks/chunk-COD3WAUI.js";import{LOCAL_SCHEDULES_SESSION_HEADER,createLocalSchedulesSession}from"../../chunks/chunk-SF4E3AQ3.js";import"../../chunks/chunk-GH6O7YJ3.js";import"../../chunks/chunk-QHJLRTVY.js";import{require_fast_deep_equal}from"../../chunks/chunk-MCRKBVZA.js";import{getUpdateCommand}from"../../chunks/chunk-Z5NJL63U.js";import{readJSONFile}from"../../chunks/chunk-FZUNGPGO.js";import"../../chunks/chunk-I7KMJTOY.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-7ENWK2AH.js";import{validateConfig}from"../../chunks/chunk-AAFST44A.js";import"../../chunks/chunk-IQ7FPAI4.js";import"../../chunks/chunk-MZ3QGJH3.js";import"../../chunks/chunk-EAUDC24V.js";import{pickOverrides}from"../../chunks/chunk-WX2KXEZV.js";import{require_dist as require_dist5}from"../../chunks/chunk-YE6WQYJH.js";import{require_brace_expansion,require_dist as require_dist3,require_dist2 as require_dist4,require_minimatch}from"../../chunks/chunk-MP27ZZFO.js";import{require_main}from"../../chunks/chunk-JHB3TYKZ.js";import"../../chunks/chunk-RRDNKB2X.js";import"../../chunks/chunk-MVGTMPMI.js";import"../../chunks/chunk-SACGQMVQ.js";import"../../chunks/chunk-BPUANOGW.js";import"../../chunks/chunk-D6REP5QQ.js";import"../../chunks/chunk-P2O5DOYE.js";import{require_raw_body}from"../../chunks/chunk-XOETL6DB.js";import"../../chunks/chunk-KKCBFBJK.js";import{VERCEL_OIDC_TOKEN}from"../../chunks/chunk-QW4W2UB6.js";import"../../chunks/chunk-EWUSBHX5.js";import{require_json_parse_better_errors}from"../../chunks/chunk-25565AGS.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-J24BABG4.js";import{pullEnvRecords}from"../../chunks/chunk-BMQREWR6.js";import{printProjectNotFoundError}from"../../chunks/chunk-WFJEWVTE.js";import"../../chunks/chunk-PNR5J6ZW.js";import"../../chunks/chunk-PVASGBEF.js";import{require_frameworks}from"../../chunks/chunk-MVCAUS4F.js";import{DEV_QUEUE_API_PREFIX,DEV_QUEUE_DEFAULT_PORT,DEV_QUEUE_PROXY_PREFIX,DEV_RESOURCE_TOKEN,DEV_RUNTIME_CACHE_DEFAULT_PORT,DEV_SCHEDULES_DEFAULT_PORT,DEV_SCHEDULES_PROXY_PREFIX,devCommand,getDevQueueEnv,getDevSchedulesEnv,isValidDevResourceHost,listenOnDevResourcePort}from"../../chunks/chunk-EVXOSCYR.js";import{require_dist as require_dist2}from"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-JXKKJ5OI.js";import"../../chunks/chunk-EVQJ7SCV.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-SCV7XEEO.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-WYI4VNXT.js";import"../../chunks/chunk-AGH2CMUM.js";import"../../chunks/chunk-IVIZLWZQ.js";import"../../chunks/chunk-HVUJNVPS.js";import{help}from"../../chunks/chunk-JJSDTLBW.js";import"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-SCJH3KSQ.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{detectExplicitScope,getLocalPathConfig,highlight}from"../../chunks/chunk-UI53O6MW.js";import{TelemetryClient}from"../../chunks/chunk-KYMABVTF.js";import"../../chunks/chunk-PUKYAALC.js";import{getGlobalPathConfig}from"../../chunks/chunk-2EYJFHEL.js";import"../../chunks/chunk-VKXEOL4K.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{isNativeBinaryInstall}from"../../chunks/chunk-NWGBDBZI.js";import"../../chunks/chunk-4SAVH3H7.js";import"../../chunks/chunk-ZS2WS4AM.js";import"../../chunks/chunk-AOWWC6WZ.js";import{directFetch}from"../../chunks/chunk-MY4MONOH.js";import{parseArguments}from"../../chunks/chunk-ZOYMKZOR.js";import"../../chunks/chunk-KJWOXBZV.js";import{buildCommandWithYes,outputActionRequired}from"../../chunks/chunk-2B2Z447M.js";import{getFlagsSpecification}from"../../chunks/chunk-4KYSK2MS.js";import{VERCEL_DIR,findRepoRoot,getLinkedProject,getVercelDirectory,require_lib,require_pluralize,resolveProjectCwd}from"../../chunks/chunk-RD7VCVW5.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import{printAlignedLabel}from"../../chunks/chunk-IJCCFLCQ.js";import"../../chunks/chunk-ZQME5XUJ.js";import"../../chunks/chunk-2VBFQZ72.js";import{CantParseJSONFile,LambdaSizeExceededError,MissingDotenvVarsError,NowError,require_bytes}from"../../chunks/chunk-XSDAUM4F.js";import{cmd,getCommandName,getCommandNamePlain,getTitleName}from"../../chunks/chunk-JESNVRVR.js";import{Diagnostic,defineDiagnostics,init_dist,link_default,output_manager_default,require_build_utils}from"../../chunks/chunk-M774HRX5.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import{pkg_default}from"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import{require_supports_color}from"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__commonJS,__require,__toESM}from"../../chunks/chunk-BZENIQ7N.js";var require_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@3.1.0/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@3.1.0/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_ms2=__commonJS({"../../node_modules/.pnpm/ms@2.0.0/node_modules/ms/index.js"(exports,module){var s=1e3,m=s*60,h=m*60,d=h*24,y=d*365.25;module.exports=function(val,options){options=options||{};var type=typeof val;if(type==="string"&&val.length>0)return parse2(val);if(type==="number"&&isNaN(val)===!1)return options.long?fmtLong(val):fmtShort(val);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(val))};function parse2(str){if(str=String(str),!(str.length>100)){var match=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);if(match){var n=parseFloat(match[1]),type=(match[2]||"ms").toLowerCase();switch(type){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(ms9){return ms9>=d?Math.round(ms9/d)+"d":ms9>=h?Math.round(ms9/h)+"h":ms9>=m?Math.round(ms9/m)+"m":ms9>=s?Math.round(ms9/s)+"s":ms9+"ms"}function fmtLong(ms9){return plural3(ms9,d,"day")||plural3(ms9,h,"hour")||plural3(ms9,m,"minute")||plural3(ms9,s,"second")||ms9+" ms"}function plural3(ms9,n,name){if(!(ms9<n))return ms9<n*1.5?Math.floor(ms9/n)+" "+name:Math.ceil(ms9/n)+" "+name+"s"}}});var require_debug=__commonJS({"../../node_modules/.pnpm/debug@3.1.0/node_modules/debug/src/debug.js"(exports,module){exports=module.exports=createDebug.debug=createDebug.default=createDebug;exports.coerce=coerce;exports.disable=disable;exports.enable=enable;exports.enabled=enabled;exports.humanize=require_ms2();exports.instances=[];exports.names=[];exports.skips=[];exports.formatters={};function selectColor(namespace){var hash=0,i;for(i in namespace)hash=(hash<<5)-hash+namespace.charCodeAt(i),hash|=0;return exports.colors[Math.abs(hash)%exports.colors.length]}function createDebug(namespace){var prevTime;function debug(){if(debug.enabled){var self2=debug,curr=+new Date,ms9=curr-(prevTime||curr);self2.diff=ms9,self2.prev=prevTime,self2.curr=curr,prevTime=curr;for(var args=new Array(arguments.length),i=0;i<args.length;i++)args[i]=arguments[i];args[0]=exports.coerce(args[0]),typeof args[0]!="string"&&args.unshift("%O");var index=0;args[0]=args[0].replace(/%([a-zA-Z%])/g,function(match,format){if(match==="%%")return match;index++;var formatter=exports.formatters[format];if(typeof formatter=="function"){var val=args[index];match=formatter.call(self2,val),args.splice(index,1),index--}return match}),exports.formatArgs.call(self2,args);var logFn=debug.log||exports.log||console.log.bind(console);logFn.apply(self2,args)}}return debug.namespace=namespace,debug.enabled=exports.enabled(namespace),debug.useColors=exports.useColors(),debug.color=selectColor(namespace),debug.destroy=destroy,typeof exports.init=="function"&&exports.init(debug),exports.instances.push(debug),debug}function destroy(){var index=exports.instances.indexOf(this);return index!==-1?(exports.instances.splice(index,1),!0):!1}function enable(namespaces){exports.save(namespaces),exports.names=[],exports.skips=[];var i,split=(typeof namespaces=="string"?namespaces:"").split(/[\s,]+/),len=split.length;for(i=0;i<len;i++)split[i]&&(namespaces=split[i].replace(/\*/g,".*?"),namespaces[0]==="-"?exports.skips.push(new RegExp("^"+namespaces.substr(1)+"$")):exports.names.push(new RegExp("^"+namespaces+"$")));for(i=0;i<exports.instances.length;i++){var instance=exports.instances[i];instance.enabled=exports.enabled(instance.namespace)}}function disable(){exports.enable("")}function enabled(name){if(name[name.length-1]==="*")return!0;var i,len;for(i=0,len=exports.skips.length;i<len;i++)if(exports.skips[i].test(name))return!1;for(i=0,len=exports.names.length;i<len;i++)if(exports.names[i].test(name))return!0;return!1}function coerce(val){return val instanceof Error?val.stack||val.message:val}}});var require_browser=__commonJS({"../../node_modules/.pnpm/debug@3.1.0/node_modules/debug/src/browser.js"(exports,module){exports=module.exports=require_debug();exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.storage=typeof chrome<"u"&&typeof chrome.storage<"u"?chrome.storage.local:localstorage();exports.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function useColors(){return typeof window<"u"&&window.process&&window.process.type==="renderer"?!0:typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)?!1:typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}exports.formatters.j=function(v){try{return JSON.stringify(v)}catch(err){return"[UnexpectedJSONParseError]: "+err.message}};function formatArgs(args){var useColors2=this.useColors;if(args[0]=(useColors2?"%c":"")+this.namespace+(useColors2?" %c":" ")+args[0]+(useColors2?"%c ":" ")+"+"+exports.humanize(this.diff),!!useColors2){var c="color: "+this.color;args.splice(1,0,c,"color: inherit");var index=0,lastC=0;args[0].replace(/%[a-zA-Z%]/g,function(match){match!=="%%"&&(index++,match==="%c"&&(lastC=index))}),args.splice(lastC,0,c)}}function log(){return typeof console=="object"&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}function save(namespaces){try{namespaces==null?exports.storage.removeItem("debug"):exports.storage.debug=namespaces}catch{}}function load(){var r;try{r=exports.storage.debug}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}exports.enable(load());function localstorage(){try{return window.localStorage}catch{}}}});var require_node=__commonJS({"../../node_modules/.pnpm/debug@3.1.0/node_modules/debug/src/node.js"(exports,module){var tty=__require("tty"),util=__require("util");exports=module.exports=require_debug();exports.init=init;exports.log=log;exports.formatArgs=formatArgs;exports.save=save;exports.load=load;exports.useColors=useColors;exports.colors=[6,2,3,4,5,1];try{supportsColor=require_supports_color(),supportsColor&&supportsColor.level>=2&&(exports.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}var supportsColor;exports.inspectOpts=Object.keys(process.env).filter(function(key){return/^debug_/i.test(key)}).reduce(function(obj,key){var prop=key.substring(6).toLowerCase().replace(/_([a-z])/g,function(_,k){return k.toUpperCase()}),val=process.env[key];return/^(yes|on|true|enabled)$/i.test(val)?val=!0:/^(no|off|false|disabled)$/i.test(val)?val=!1:val==="null"?val=null:val=Number(val),obj[prop]=val,obj},{});function useColors(){return"colors"in exports.inspectOpts?!!exports.inspectOpts.colors:tty.isatty(process.stderr.fd)}exports.formatters.o=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts).split(`
|
|
8
8
|
`).map(function(str){return str.trim()}).join(" ")};exports.formatters.O=function(v){return this.inspectOpts.colors=this.useColors,util.inspect(v,this.inspectOpts)};function formatArgs(args){var name=this.namespace,useColors2=this.useColors;if(useColors2){var c=this.color,colorCode="\x1B[3"+(c<8?c:"8;5;"+c),prefix=" "+colorCode+";1m"+name+" \x1B[0m";args[0]=prefix+args[0].split(`
|
|
9
9
|
`).join(`
|
|
10
10
|
`+prefix),args.push(colorCode+"m+"+exports.humanize(this.diff)+"\x1B[0m")}else args[0]=getDate()+name+" "+args[0]}function getDate(){return exports.inspectOpts.hideDate?"":new Date().toISOString()+" "}function log(){return process.stderr.write(util.format.apply(util,arguments)+`
|
|
@@ -20,7 +20,7 @@ globstar while`,file,fr,pattern,pr,swallowee),this.matchOne(file.slice(fr),patte
|
|
|
20
20
|
`),result={variables:{},expressions:[],errors:{}};for(let block of blocks){let entry=block.trim();if(entry.length===0||entry.startsWith("#"))continue;let variableMatch=entry.match(/^(.*)=(.*)$/);if(variableMatch){let[,key,value]=variableMatch;result.variables[key]=value.replace(/["']/g,"");continue}try{let parsedEntry=_CronFileParser.#parseEntry(entry);result.expressions.push(parsedEntry.interval)}catch(err){result.errors[entry]=err}}return result}static#parseEntry(entry){let atoms=entry.split(" ");return{interval:CronExpressionParser_1.CronExpressionParser.parse(atoms.slice(0,5).join(" ")),command:atoms.slice(5,atoms.length)}}};exports.CronFileParser=CronFileParser}});var require_dist8=__commonJS({"../../node_modules/.pnpm/cron-parser@5.4.0/node_modules/cron-parser/dist/index.js"(exports){"use strict";var __createBinding=exports&&exports.__createBinding||(Object.create?function(o,m,k,k2){k2===void 0&&(k2=k);var desc=Object.getOwnPropertyDescriptor(m,k);(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable))&&(desc={enumerable:!0,get:function(){return m[k]}}),Object.defineProperty(o,k2,desc)}:function(o,m,k,k2){k2===void 0&&(k2=k),o[k2]=m[k]}),__exportStar=exports&&exports.__exportStar||function(m,exports2){for(var p in m)p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p)&&__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:!0});exports.CronFileParser=exports.CronExpressionParser=exports.CronExpression=exports.CronFieldCollection=exports.CronDate=void 0;var CronExpressionParser_1=require_CronExpressionParser(),CronDate_1=require_CronDate();Object.defineProperty(exports,"CronDate",{enumerable:!0,get:function(){return CronDate_1.CronDate}});var CronFieldCollection_1=require_CronFieldCollection();Object.defineProperty(exports,"CronFieldCollection",{enumerable:!0,get:function(){return CronFieldCollection_1.CronFieldCollection}});var CronExpression_1=require_CronExpression();Object.defineProperty(exports,"CronExpression",{enumerable:!0,get:function(){return CronExpression_1.CronExpression}});var CronExpressionParser_2=require_CronExpressionParser();Object.defineProperty(exports,"CronExpressionParser",{enumerable:!0,get:function(){return CronExpressionParser_2.CronExpressionParser}});var CronFileParser_1=require_CronFileParser();Object.defineProperty(exports,"CronFileParser",{enumerable:!0,get:function(){return CronFileParser_1.CronFileParser}});__exportStar(require_fields(),exports);exports.default=CronExpressionParser_1.CronExpressionParser}});var require_types2=__commonJS({"../../internals/local-schedules/dist/types.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),types_exports={};__export(types_exports,{ScheduleBrokerError:()=>ScheduleBrokerError2});module.exports=__toCommonJS(types_exports);var ScheduleBrokerError2=class extends Error{constructor(code,message){super(message),this.code=code,this.name="ScheduleBrokerError"}}}});var require_timing=__commonJS({"../../internals/local-schedules/dist/timing.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),timing_exports={};__export(timing_exports,{nextCronOccurrence:()=>nextCronOccurrence,nextOccurrence:()=>nextOccurrence,singleOccurrence:()=>singleOccurrence,validateCronJitter:()=>validateCronJitter,validateTimezone:()=>validateTimezone});module.exports=__toCommonJS(timing_exports);var import_cron_parser=require_dist8(),import_luxon=__require("luxon"),import_types=require_types2();function invalid(message){throw new import_types.ScheduleBrokerError("invalid_request",message)}function validateTimezone(timezone){(timezone.length>50||!/^[A-Za-z][A-Za-z0-9_+/-]*$/.test(timezone))&&invalid("Expected a valid IANA timezone");try{new Intl.DateTimeFormat("en-US",{timeZone:timezone})}catch{invalid("Expected a valid IANA timezone")}}function parseCron(cron,timezone,after){let fields=cron.split(" ");(fields.length!==5||fields.some(field=>!/^[\d*,/-]+$/.test(field))||fields[2]!=="*"&&fields[4]!=="*"||fields[4].split(/\D+/).some(value=>Number(value)>6))&&invalid("Expected a numeric five-field cron; one of day-of-month/day-of-week must be *, Sunday is 0");try{return import_cron_parser.CronExpressionParser.parse(`0 ${cron}`,{currentDate:after,tz:timezone,strict:!0})}catch(error2){invalid(`Invalid cron: ${error2 instanceof Error?error2.message:String(error2)}`)}}function validateCronJitter(cron,timezone,jitter){let{fields}=parseCron(cron,timezone,0),times=fields.hour.values.flatMap(hour=>fields.minute.values.map(minute=>hour*60+minute)),dayCycle=1440,[,,dayOfMonth,month,dayOfWeek]=cron.split(" ");if(dayOfMonth==="*"&&month==="*"&&dayOfWeek!=="*"){let days=fields.dayOfWeek.values.map(Number),gap=7-days[days.length-1]+days[0];for(let i=1;i<days.length;i++)gap=Math.min(gap,days[i]-days[i-1]);dayCycle*=gap}let cadence=dayCycle-times[times.length-1]+times[0];for(let i=1;i<times.length;i++)cadence=Math.min(cadence,times[i]-times[i-1]);jitter>cadence&&invalid("Jitter exceeds the cron cadence")}function nextCronOccurrence(cron,timezone,after){let iterator=parseCron(cron,timezone,after);for(let attempt=0;attempt<1500;attempt++){let timestamp;try{timestamp=iterator.next().getTime()}catch{invalid("Cron has no calculable next occurrence")}let local=import_luxon.DateTime.fromMillis(timestamp,{zone:timezone}),fields=iterator.fields;if(!fields.hour.values.some(hour=>hour===local.hour)||!fields.minute.values.some(minute=>minute===local.minute))continue;let first=Math.min(...local.getPossibleOffsets().map(date=>date.toMillis()));if(timestamp===first)return timestamp}invalid("Could not resolve cron across timezone transitions")}function singleOccurrence(at,timezone){/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/.test(at)||invalid("Expected YYYY-MM-DDTHH:mm:ss without a timezone suffix");let local=import_luxon.DateTime.fromISO(at,{zone:timezone});return(!local.isValid||local.toFormat("yyyy-MM-dd'T'HH:mm:ss")!==at)&&invalid("One-shot time is invalid or nonexistent in its timezone"),local.getPossibleOffsets().length!==1&&invalid("Ambiguous one-shot time in its timezone"),local.toMillis()}function nextOccurrence(expression,timezone,after){if(expression.type==="cron")return nextCronOccurrence(expression.cron,timezone,after);expression.type!=="single"&&invalid("Unknown schedule expression type");let at=singleOccurrence(expression.at,timezone);return at>=after?at:void 0}}});var require_schedule_broker=__commonJS({"../../internals/local-schedules/dist/schedule-broker.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),schedule_broker_exports={};__export(schedule_broker_exports,{ScheduleBroker:()=>ScheduleBroker3});module.exports=__toCommonJS(schedule_broker_exports);var import_node_crypto2=__require("node:crypto"),import_node_util=__require("node:util"),import_dispatch=require_dispatch(),import_ids=require_ids(),import_timing=require_timing(),import_types=require_types2(),MAX_TIMER_DELAY=6e4;function invalid(message){throw new import_types.ScheduleBrokerError("invalid_request",message)}function identifier2(value){return(typeof value!="string"||!/^[0-9A-Za-z._-]{1,256}$/.test(value))&&invalid("Invalid schedule name or namespace"),value}function keyOf(input){return`${identifier2(input.namespace??"default")}/${identifier2(input.name)}`}function serializePayload(payload){if(payload!==void 0)try{let result=JSON.stringify(payload);return result===void 0&&invalid("Payload must be JSON serializable"),result}catch{invalid("Payload must be JSON serializable")}}function prepare(input,now){let timezone=input.timezone??"UTC";(0,import_timing.validateTimezone)(timezone),input.jitter!==void 0&&(!Number.isInteger(input.jitter)||input.jitter<1||input.jitter>15)&&invalid("Jitter must be an integer from 1 to 15 minutes");let target=input.target,targetRef=target?.type==="queue"?target.topic:target?.type==="function"?target.function:target?.type==="path"?target.path:void 0;(!target||target.type!=="queue"&&target.type!=="function"&&target.type!=="path"||typeof targetRef!="string"||!targetRef)&&invalid("Expected a queue topic, function, or path target"),target.type==="path"&&target.requestMethod!==void 0&&target.requestMethod!=="GET"&&target.requestMethod!=="POST"&&invalid("Path target requestMethod must be GET or POST");let next=(0,import_timing.nextOccurrence)(input.expression,timezone,now);return input.expression.type==="cron"&&input.jitter!==void 0&&(0,import_timing.validateCronJitter)(input.expression.cron,timezone,input.jitter),{expression:{...input.expression},timezone,...input.jitter===void 0?{}:{jitter:input.jitter},target:{...target},payload:serializePayload(input.payload),next}}var ScheduleBroker3=class{constructor(options){this.options=options,this.entries=new Map,this.inFlight=new Set,this.running=!1,this.closed=!1,this.scope={ownerId:options.ownerId,projectId:options.projectId,trackId:options.trackId},Object.values(this.scope).some(value=>typeof value!="string"||!value)&&invalid("An owner, project, and track are required"),this.now=options.now??Date.now,this.random=options.random??Math.random}start(){this.assertOpen(),this.running=!0,this.arm()}create(input){this.assertOpen(),input.target.type!=="queue"&&invalid("Dynamic schedules require a queue target");let name=input.name??`dyn.${(0,import_node_crypto2.randomBytes)(12).toString("hex")}`,key=keyOf({...input,name});if(this.entries.has(key))throw new import_types.ScheduleBrokerError("conflict",`Schedule ${key} already exists`);let entry=this.insert({...input,name},prepare(input,this.now()),"dynamic");return this.arm(),structuredClone(entry.schedule)}get(input){return structuredClone(this.require(input).schedule)}list(input={}){let namespace=identifier2(input.namespace??"default"),limit=input.limit??20;(!Number.isInteger(limit)||limit<1||limit>100)&&invalid("Limit must be between 1 and 100");let after="",scope=[this.scope.ownerId,this.scope.projectId,this.scope.trackId,namespace];if(input.cursor!==void 0)try{let cursor=JSON.parse(Buffer.from(input.cursor,"base64url").toString());(!Array.isArray(cursor)||cursor.length!==5||!scope.every((value,i)=>value===cursor[i]))&&invalid("Invalid list cursor"),after=identifier2(cursor[4])}catch{invalid("Invalid list cursor")}let records=[...this.entries.values()].map(entry=>entry.schedule).filter(schedule=>schedule.namespace===namespace&&schedule.name>after).sort((a,b)=>a.name<b.name?-1:a.name>b.name?1:0),data=records.slice(0,limit);return{data:structuredClone(data),cursor:records.length>limit?Buffer.from(JSON.stringify([...scope,data[data.length-1].name])).toString("base64url"):null}}update(input,changes){this.assertOpen();let entry=this.require(input);changes.target&&changes.target.type!=="queue"&&invalid("Management updates require a queue target");let prepared=prepare({...entry.schedule,...changes,expression:changes.expression??entry.schedule.expression,timezone:changes.timezone??entry.schedule.timezone,target:changes.target??entry.schedule.target,jitter:changes.jitter===null?void 0:changes.jitter??entry.schedule.jitter,payload:changes.payload===void 0?entry.payload===void 0?void 0:JSON.parse(entry.payload):changes.payload===null?void 0:changes.payload},this.schedulingBoundary(entry));return this.replace(entry,prepared),this.arm(),structuredClone(entry.schedule)}delete(input){this.assertOpen();let entry=this.require(input);return this.cancel(entry),this.entries.delete(keyOf(input)),this.arm(),{scheduleId:entry.schedule.scheduleId}}enable(input){return this.setState(input,"active")}disable(input){return this.setState(input,"inactive")}validateStatic(inputs){this.prepareStatic(inputs)}prepareStatic(inputs){this.assertOpen();let prepared=new Map;for(let input of inputs){"payload"in input&&invalid("Static schedule definitions cannot include a payload");let key=keyOf(input),existing=this.entries.get(key);if(prepared.has(key)||existing?.schedule.source==="dynamic")throw new import_types.ScheduleBrokerError("conflict",`Static schedule ${key} conflicts with an existing definition`);prepared.set(key,{input,value:{...prepare(input,this.schedulingBoundary(existing)),payload:existing?.payload}})}return prepared}reconcileStatic(inputs){let prepared=this.prepareStatic(inputs);for(let[key,entry]of this.entries)entry.schedule.source==="static"&&!prepared.has(key)&&(this.cancel(entry),this.entries.delete(key));let result=[];for(let[key,{input,value}]of prepared){let existing=this.entries.get(key),entry=existing??this.insert(input,value,"static");existing&&!this.matches(existing,value)&&this.replace(existing,value),result.push(structuredClone(entry.schedule))}return this.arm(),result}async invoke(input){this.assertOpen();let entry=this.require(input),at=this.now();await this.dispatch(entry,at,"manual")}async close(){this.closed=!0,this.running=!1,this.timer&&clearTimeout(this.timer),this.timer=void 0;for(let entry of this.entries.values())this.cancel(entry);await Promise.allSettled([...this.inFlight])}assertOpen(){if(this.closed)throw new import_types.ScheduleBrokerError("closed","Schedule broker is closed")}require(input){let key=keyOf(input),entry=this.entries.get(key);if(!entry)throw new import_types.ScheduleBrokerError("not_found",`Schedule ${key} not found`);return entry}insert(input,value,source){let{payload,next,...definition2}=value,now=this.now(),entry={schedule:{ownerId:this.scope.ownerId,projectId:this.scope.projectId,...definition2,scheduleId:(0,import_ids.generateScheduleId)(),name:input.name,namespace:input.namespace??"default",state:"active",source,createdAt:now,updatedAt:now},payload,next,consumed:!1,pending:new Map,controllers:new Set};return this.entries.set(keyOf(input),entry),entry}matches(entry,value){return(0,import_node_util.isDeepStrictEqual)(entry.schedule.expression,value.expression)&&(0,import_node_util.isDeepStrictEqual)(entry.schedule.target,value.target)&&entry.schedule.timezone===value.timezone&&entry.schedule.jitter===value.jitter&&entry.payload===value.payload}replace(entry,value){this.cancel(entry),(!(0,import_node_util.isDeepStrictEqual)(entry.schedule.expression,value.expression)||entry.schedule.timezone!==value.timezone)&&(entry.consumed=!1);let{payload,next,...definition2}=value;entry.schedule={...entry.schedule,...definition2,jitter:value.jitter,updatedAt:this.now()},entry.payload=payload,entry.next=entry.consumed||entry.schedule.state!=="active"?void 0:next}setState(input,state){this.assertOpen();let entry=this.require(input);if(entry.schedule.state!==state){let next=state==="active"&&!entry.consumed?(0,import_timing.nextOccurrence)(entry.schedule.expression,entry.schedule.timezone,this.schedulingBoundary(entry)):void 0;this.cancel(entry),entry.schedule={...entry.schedule,state,updatedAt:this.now()},entry.next=next,this.arm()}return structuredClone(entry.schedule)}schedulingBoundary(entry){return Math.max(this.now(),(entry?.lastScheduledAt??-1/0)+1)}cancel(entry){entry.next=void 0,entry.pending.clear();for(let controller of entry.controllers)controller.abort();entry.controllers.clear()}arm(){if(this.timer&&clearTimeout(this.timer),this.timer=void 0,!this.running)return;let deadline=1/0;for(let entry of this.entries.values()){entry.next!==void 0&&(deadline=Math.min(deadline,entry.next));for(let due of entry.pending.values())deadline=Math.min(deadline,due)}Number.isFinite(deadline)&&(this.timer=setTimeout(()=>this.tick(),Math.max(0,Math.min(MAX_TIMER_DELAY,deadline-this.now()))),this.timer.unref())}tick(){if(this.timer=void 0,!this.running)return;let now=this.now();for(let entry of this.entries.values()){if(entry.next!==void 0&&entry.next<=now){let at=entry.next;entry.lastScheduledAt=at;let offset=entry.schedule.jitter===void 0?0:Math.floor(this.random()*(entry.schedule.jitter*60+1))*1e3;entry.pending.set(at,at+offset),entry.next=entry.schedule.expression.type==="cron"?(0,import_timing.nextOccurrence)(entry.schedule.expression,entry.schedule.timezone,now):void 0}for(let[at,due]of entry.pending)due>now||(entry.pending.delete(at),this.dispatch(entry,at,"scheduled"))}this.arm()}dispatch(entry,at,source){let controller=new AbortController;entry.controllers.add(controller);let invocation=(0,import_dispatch.createDispatch)(structuredClone(entry.schedule),entry.payload,at,(0,import_ids.scheduleExecutionId)(entry.schedule.scheduleId,at),source,controller.signal),promise=Promise.resolve().then(async()=>{if(!(this.closed||controller.signal.aborted)){source==="scheduled"&&entry.schedule.expression.type==="single"&&(entry.consumed=!0);try{await this.options.dispatch(invocation)}catch(error2){if(controller.signal.aborted)return;if(source==="manual")throw error2;try{this.options.onError(error2,invocation)}catch{}}}}).finally(()=>{entry.controllers.delete(controller),this.inFlight.delete(promise)});return this.inFlight.add(promise),promise}}}});var require_dist9=__commonJS({"../../internals/local-schedules/dist/index.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__reExport=(target,mod,secondTarget)=>(__copyProps(target,mod,"default"),secondTarget&&__copyProps(secondTarget,mod,"default")),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),src_exports={};__export(src_exports,{ScheduleBroker:()=>import_schedule_broker.ScheduleBroker});module.exports=__toCommonJS(src_exports);var import_schedule_broker=require_schedule_broker();__reExport(src_exports,require_types2(),module.exports)}});var require_tree_kill=__commonJS({"../../node_modules/.pnpm/tree-kill@1.2.2/node_modules/tree-kill/index.js"(exports,module){"use strict";var childProcess=__require("child_process"),spawn=childProcess.spawn,exec=childProcess.exec;module.exports=function(pid,signal,callback){if(typeof signal=="function"&&callback===void 0&&(callback=signal,signal=void 0),pid=parseInt(pid),Number.isNaN(pid)){if(callback)return callback(new Error("pid must be a number"));throw new Error("pid must be a number")}var tree={},pidsToProcess={};switch(tree[pid]=[],pidsToProcess[pid]=1,process.platform){case"win32":exec("taskkill /pid "+pid+" /T /F",callback);break;case"darwin":buildProcessTree(pid,tree,pidsToProcess,function(parentPid){return spawn("pgrep",["-P",parentPid])},function(){killAll(tree,signal,callback)});break;default:buildProcessTree(pid,tree,pidsToProcess,function(parentPid){return spawn("ps",["-o","pid","--no-headers","--ppid",parentPid])},function(){killAll(tree,signal,callback)});break}};function killAll(tree,signal,callback){var killed={};try{Object.keys(tree).forEach(function(pid){tree[pid].forEach(function(pidpid){killed[pidpid]||(killPid(pidpid,signal),killed[pidpid]=1)}),killed[pid]||(killPid(pid,signal),killed[pid]=1)})}catch(err){if(callback)return callback(err);throw err}if(callback)return callback()}function killPid(pid,signal){try{process.kill(parseInt(pid,10),signal)}catch(err){if(err.code!=="ESRCH")throw err}}function buildProcessTree(parentPid,tree,pidsToProcess,spawnChildProcessesList,cb){var ps=spawnChildProcessesList(parentPid),allData="";ps.stdout.on("data",function(data){var data=data.toString("ascii");allData+=data});var onClose=function(code){if(delete pidsToProcess[parentPid],code!=0){Object.keys(pidsToProcess).length==0&&cb();return}allData.match(/\d+/g).forEach(function(pid){pid=parseInt(pid,10),tree[parentPid].push(pid),tree[pid]=[],pidsToProcess[pid]=1,buildProcessTree(pid,tree,pidsToProcess,spawnChildProcessesList,cb)})};ps.on("close",onClose)}}});var require_escape_html=__commonJS({"../../node_modules/.pnpm/escape-html@1.0.3/node_modules/escape-html/index.js"(exports,module){"use strict";var matchHtmlRegExp=/["'&<>]/;module.exports=escapeHtml;function escapeHtml(string){var str=""+string,match=matchHtmlRegExp.exec(str);if(!match)return str;var escape2,html="",index=0,lastIndex=0;for(index=match.index;index<str.length;index++){switch(str.charCodeAt(index)){case 34:escape2=""";break;case 38:escape2="&";break;case 39:escape2="'";break;case 60:escape2="<";break;case 62:escape2=">";break;default:continue}lastIndex!==index&&(html+=str.substring(lastIndex,index)),lastIndex=index+1,html+=escape2}return lastIndex!==index?html+str.substring(lastIndex,index):html}}});var import_chalk4=__toESM(require_source(),1);import path5 from"path";var import_chalk3=__toESM(require_source(),1),import_ms8=__toESM(require_ms(),1),import_fs_extra2=__toESM(require_lib(),1),import_fs_detectors3=__toESM(require_dist4(),1),import_frameworks4=__toESM(require_frameworks(),1),import_build_utils10=__toESM(require_build_utils(),1);import{resolve as resolve2,join as join6}from"path";var import_fs_extra=__toESM(require_lib(),1),import_ms6=__toESM(require_ms(),1),import_chalk2=__toESM(require_source(),1);import url3,{URL as URL2}from"url";import http from"http";import{Socket}from"net";var import_pluralize2=__toESM(require_pluralize(),1),import_raw_body2=__toESM(require_raw_body(),1),import_async_listen=__toESM(require_dist2(),1),import_minimatch3=__toESM(require_minimatch(),1),import_http_proxy_node16=__toESM(require_http_proxy_node16(),1),import_serve_handler=__toESM(require_src2(),1),import_pcre_to_regexp2=__toESM(require_dist6(),1),import_dotenv=__toESM(require_main(),1),import_once=__toESM(require_dist7(),1),import_directory=__toESM(require_directory(),1),import_get_port2=__toESM(require_get_port(),1),import_fast_deep_equal=__toESM(require_fast_deep_equal(),1);import{randomBytes as randomBytes2,timingSafeEqual}from"crypto";import{watch}from"chokidar";import path4,{isAbsolute as isAbsolute3,basename,dirname as dirname3,extname as extname2,join as join4,sep as sep2}from"path";var import_is_port_reachable=__toESM(require_is_port_reachable(),1);init_dist();var import_build_utils=__toESM(require_build_utils(),1),import_ms=__toESM(require_ms(),1);var REPORT_A_BUG="This is likely a bug in the Vercel CLI. Please report it at https://vercel.com/help.",REPORT_A_BUILDER_BUG="This is likely a bug in the Builder that produced this function. Report it to the Builder's author, or at https://vercel.com/help for an official `@vercel/*` Builder.",dev=defineDiagnostics({codes:{DEV_RECURSIVE_INVOCATION:{why:"`vercel dev` must not recursively invoke itself",fix:"Check the Development Command in your Project Settings and the `dev` script in `package.json` \u2014 neither should call `vercel dev`.",docs:"https://vercel.link/recursive-invocation-of-commands"},DEV_LOCK_HELD:{why:"Another `vercel dev` process is already running for this project",fix:p=>p.detail},DEV_INVALID_WINDOWS_PIPE:{why:p=>`Invalid Windows named pipe endpoint: ${p.endpoint}`,fix:"Use a pipe path beginning with `\\\\.\\`, e.g. `pipe:\\\\.\\pipe\\my-app`."},DEV_INVALID_UNIX_SOCKET:{why:p=>`Invalid UNIX domain socket endpoint: ${p.endpoint}`,fix:"Provide a socket path, e.g. `unix:/tmp/my-app.sock`."},DEV_INVALID_LISTEN_SCHEME:{why:p=>`Unknown \`--listen\` scheme (protocol): ${p.protocol}`,fix:"Use a port (e.g. `3000`), or a `tcp:`, `unix:`, or `pipe:` endpoint."},DEV_PORT_DETECTION_TIMED_OUT:{why:p=>`Detecting port ${p.port} timed out after ${(0,import_ms.default)(p.timeout)}`,fix:"Ensure your Development Command starts a server that listens on the expected port."},DEV_BUILDER_LOAD_FAILED:{why:p=>`Failed to load Builder "${p.use}"`,fix:"Check that the Builder is installed and spelled correctly in your `vercel.json` `builds` configuration."},DEV_SIDECAR_UNSUPPORTED_TYPE:{why:p=>`Development sidecar "${p.name}" has unsupported type "${p.type}"`,fix:REPORT_A_BUILDER_BUG},DEV_SIDECAR_DUPLICATE_NAME:{why:p=>`Multiple builders contributed a development sidecar named "${p.name}"`,fix:REPORT_A_BUILDER_BUG},DEV_QUEUE_CONSUMER_DUPLICATE:{why:p=>`Queue consumer "${p.consumerGroup}" is configured more than once for topic "${p.topic}"`,fix:"Remove the duplicate consumer configuration so each consumer subscribes to a topic only once."},DEV_QUEUE_FUNCTION_UNSUPPORTED:{why:p=>`Can't register the queue trigger for "${p.sourceFile}": ${p.reason}.`,fix:"Use an endpoint supported by the builder for local queue delivery, or test this trigger in a deployment."},DEV_FUNCTION_MANIFEST_INVALID:{why:p=>`Builder "${p.use}" returned an invalid development function manifest.`,fix:"Check getDevManifest output identities, invocation paths, and normalized trigger metadata. Paths must not contain an origin, query, fragment, or traversal."},DEV_FUNCTION_OUTPUT_DUPLICATE:{why:p=>`Development function output "${p.outputPath}" is configured more than once.`,fix:"Each deployment function output must have one owner."},DEV_SCHEDULE_FUNCTION_MISSING:{why:p=>`Schedule "${p.name}" targets missing development function "${p.outputPath}".`,fix:"Use the exact build output ID, not a source path or URL. The builder must expose it through getDevManifest or a supported per-entrypoint function build; service-hosted targets are not supported locally yet."},DEV_SCHEDULE_FUNCTION_TRIGGER:{why:p=>`Schedule "${p.name}" targets function "${p.outputPath}" without a sole schedule/v1beta trigger.`,fix:'Declare experimentalTriggers: [{ "type": "schedule/v1beta" }] on the target function, or have its builder return that trigger in getDevManifest.'},DEV_QUEUE_FUNCTION_UNMATCHED:{why:p=>`No local queue endpoint matches functions["${p.pattern}"]. Its queue trigger will not receive messages.`,fix:"Check the source path and earlier functions entries. The builder must support getDevManifest or a conventional per-entrypoint function build."},DEV_SERVICE_NO_DEV_SERVER:{why:p=>`No dev server available for service "${p.name}" (framework: ${p.framework})`,fix:"Add a Development Command for this service, or set its framework so one can be detected."},DEV_SERVICE_NO_PID:{why:p=>`Failed to start service "${p.name}": no PID returned`,fix:"Verify the service Development Command is executable and starts successfully."},DEV_SERVICE_NO_STDIO:{why:p=>`Failed to start service "${p.name}": expected child process to have stdout and stderr`,fix:REPORT_A_BUG},DEV_BUILDER_RESULT_NOT_LAMBDA:{why:'The result of "builder.build()" must be a `Lambda`',fix:REPORT_A_BUILDER_BUG},DEV_BUILDER_RESULT_HAS_MAXDURATION:{why:'The result of "builder.build()" must not contain `maxDuration`',fix:REPORT_A_BUILDER_BUG},DEV_BUILDER_RESULT_HAS_MEMORY:{why:'The result of "builder.build()" must not contain `memory`',fix:REPORT_A_BUILDER_BUG},DEV_UNSUPPORTED_BUILDER_VERSION:{why:p=>`${p.titleName} CLI does not support builder version ${p.version}`,fix:p=>p.updateMessage},DEV_INVALID_ROUTES:{why:p=>p.message,fix:REPORT_A_BUILDER_BUG},DEV_LISTEN_ADDRESS_IN_USE:{why:p=>`Requested socket ${p.address} is already in use`,fix:"Stop the process using that socket, or pass a different `--listen` address."},DEV_COMMAND_PORT_IN_USE:{why:p=>`Port ${p.port} is already in use`,fix:"Stop the process listening on it, or pass a different `--listen` port."},DEV_UNSUPPORTED_CONFIG_VERSION:{why:"Cannot run `version: 1` projects",fix:'Upgrade the project to the current configuration \u2014 remove `"version": 1` from your `vercel.json`.'},DEV_CWD_NOT_FOUND:{why:p=>`Directory \`${p.cwd}\` does not exist`,fix:"Run the command from an existing directory, or pass a valid path."},DEV_CWD_NOT_DIRECTORY:{why:p=>`Path \`${p.cwd}\` is not a directory`,fix:"Point the command at a directory rather than a file."},DEV_INTERNAL_ADDRESS_UNAVAILABLE:{why:"Invalid access to `address` because `start` has not yet populated `this.address`",fix:REPORT_A_BUG},DEV_INTERNAL_NO_ROUTE_RESULT:{why:"Expected Route Result but none was found",fix:REPORT_A_BUG},DEV_INTERNAL_MISSING_CHILD_STDIO:{why:"Expected child process to have stdout and stderr",fix:REPORT_A_BUG},DEV_SYSCALL_ERROR:{why:p=>p.message,fix:"This is an operating-system error. Check the file path, permissions, and ports referenced above, then retry."}}});function toDiagnostic2(err){return toDiagnostic(err,{syscall:(message,cause)=>dev.DEV_SYSCALL_ERROR({message,cause})})}var DevCommandExitError=class extends Diagnostic{constructor(message,exitCode){super({why:message,fix:"Your Development Command exited before the dev server was ready. Fix the error logged above, then confirm the command runs on its own (e.g. `npm run dev`)."});this.name="DEV_COMMAND_EXITED",this.exitCode=exitCode}},ServiceStartError=class extends Diagnostic{constructor(failures){let dedupeErrorCodes=new Set(["PYTHON_EXTERNAL_VENV_DETECTED"]),seenCodes=new Set,uniqueMessages=[],childFixes=[],childCodes=[];for(let err of failures){let message=err instanceof Error?err.message:String(err),rawCode=err?.code,code=err instanceof import_build_utils.NowBuildError?err.code:typeof rawCode=="string"?rawCode:void 0;code&&dedupeErrorCodes.has(code)?seenCodes.has(code)||(uniqueMessages.push(message),seenCodes.add(code)):uniqueMessages.push(message),code&&!childCodes.includes(code)&&childCodes.push(code);let childFix=code&&Object.hasOwn(FIX_BY_CODE,code)?FIX_BY_CODE[code]:void 0;childFix&&!childFixes.includes(childFix)&&childFixes.push(childFix)}super({why:uniqueMessages.join(`
|
|
21
21
|
`),fix:childFixes.length?childFixes.join(`
|
|
22
22
|
`):"Review the per-service errors above and fix each failing service before retrying."});this.name="DEV_SERVICE_START_FAILED",this.childCodes=childCodes}};function telemetryCodes(diagnostic){return diagnostic instanceof ServiceStartError&&diagnostic.childCodes.length?diagnostic.childCodes:[diagnostic.name]}function sleep(ms9){return new Promise(resolve3=>setTimeout(resolve3,ms9))}async function getReachableHostOnPort(port){let optsIpv4={host:"127.0.0.1"},optsIpv6={host:"::1"};return(await Promise.all([(0,import_is_port_reachable.default)(port,optsIpv6).then(r=>r&&`[${optsIpv6.host}]`),(0,import_is_port_reachable.default)(port,optsIpv4).then(r=>r&&optsIpv4.host)])).find(Boolean)||!1}async function waitForPortToFree(port,timeout=0){let start=Date.now();for(;await getReachableHostOnPort(port);){if(Date.now()-start>=timeout)return!1;await sleep(100)}return!0}async function checkForPort(port,timeout){let host,start=Date.now();for(;!(host=await getReachableHostOnPort(port))&&!(Date.now()-start>timeout);)await sleep(100);if(!host)throw dev.DEV_PORT_DETECTION_TIMED_OUT({port,timeout});return host}var import_npm_package_arg=__toESM(require_npa(),1),import_json_parse_better_errors=__toESM(require_json_parse_better_errors(),1),import_client=__toESM(require_dist5(),1),import_routing_utils3=__toESM(require_dist3(),1),import_build_utils9=__toESM(require_build_utils(),1),import_fs_detectors2=__toESM(require_dist4(),1),import_detect_builders_with_services=__toESM(require_detect_builders_with_services(),1),import_schedule_entrypoint=__toESM(require_schedule_entrypoint(),1),import_frameworks3=__toESM(require_frameworks(),1),import_local_schedules2=__toESM(require_dist9(),1);var import_build_utils2=__toESM(require_build_utils(),1);import{relative as nativeRelative}from"path";function relative(a,b){return(0,import_build_utils2.normalizePath)(nativeRelative(a,b))}var import_get_files=__toESM(require_get_files(),1);function staticFiles(path6,options){return(0,import_get_files.staticFiles)(path6,options,output_manager_default)}var import_pcre_to_regexp=__toESM(require_dist6(),1);import url2 from"url";function isURL(str){return typeof str=="string"&&/^https?:\/\//.test(str)}var import_routing_utils=__toESM(require_dist3(),1);function parseQueryString(querystring){let query=Object.create(null);if(!querystring||!querystring.startsWith("?")||querystring==="?")return query;let params=querystring.slice(1).split("&");for(let param2 of params){let[key,value]=param2.split("=");key!==void 0&&(key=decodeURIComponent(key)),value!==void 0&&(value=decodeURIComponent(value));let existing=query[key];existing||(existing=[],query[key]=existing),existing.push(value)}return query}function formatQueryString(query){if(!query)return null;let s="",prefix="?";for(let[key,values]of Object.entries(query))for(let value of values)s+=prefix,s+=encodeURIComponent(key),value!==void 0&&(s+="=",s+=encodeURIComponent(value)),prefix="&";return s||null}import url from"url";function resolveTransforms(transforms,ctx){return!transforms||transforms.length===0?[]:transforms.map(transform=>transform.type==="request.path"?{...transform,args:resolveString(transform.args,transform,ctx)}:{...transform,target:{key:resolveKey(transform.target.key,transform,ctx)},args:resolveArgs(transform.args,transform,ctx)})}function applyResponseTransforms(headers,transforms){for(let transform of transforms)transform.type==="response.headers"&&"target"in transform&&applyTransform(headers,transform,!0)}function applyRequestTransforms(req,transforms){if(transforms.length===0)return;applyRequestHeaderTransforms(req.headers,transforms);let parsed=url.parse(req.url||"/"),query=parseQueryString(parsed.search);applyQueryTransforms(query,transforms);let newPath=getRequestPath(transforms);newPath!==void 0&&(parsed.pathname=newPath),parsed.search=formatQueryString(query),req.url=url.format(parsed)}function hasResponseTransforms(transforms){return transforms.some(t=>t.type==="response.headers")}function resolveKey(key,_transform,ctx){return typeof key=="string"?expandCaptureGroups(key,ctx.match,ctx.keys):key}function resolveArgs(args,transform,ctx){return typeof args=="string"?resolveString(args,transform,ctx):Array.isArray(args)?args.map(a=>typeof a=="string"?resolveString(a,transform,ctx):a):args}function resolveString(value,transform,ctx){let resolved=expandCaptureGroups(value,ctx.match,ctx.keys);return transform.env&&transform.env.length>0&&ctx.env&&(resolved=expandEnvVars(resolved,transform.env,ctx.env)),resolved}function expandCaptureGroups(str,match,keys){return str.replace(/\$([0-9A-Za-z_]+)/g,(whole,name)=>{let namedIdx=keys.indexOf(name);if(namedIdx!==-1)return match[namedIdx+1]??"";if(/^[0-9]+$/.test(name)){let n=parseInt(name,10);if(n<match.length)return match[n]??""}return whole})}function expandEnvVars(str,allowlist,env){let allowed=new Set(allowlist);return str.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g,(match,braced,bare)=>{let name=braced??bare;return!allowed.has(name)||env[name]===void 0?match:env[name]})}function applyRequestHeaderTransforms(headers,transforms){for(let transform of transforms)transform.type==="request.headers"&&"target"in transform&&applyTransform(headers,transform,!0)}function applyQueryTransforms(query,transforms){for(let transform of transforms)transform.type==="request.query"&&"target"in transform&&applyTransform(query,transform,!1);for(let key of Object.keys(query)){let value=query[key];value===void 0?delete query[key]:typeof value=="string"&&(query[key]=[value])}}var HEADER_NAME_RE=/^[-\w]+$/,HEADER_VALUE_RE=/^[-\w:;.,/\\"'?!(){}[\]@<>=+*#$&`|~%^ ]+$/;function isValidHeaderName(name){return name.length>0&&HEADER_NAME_RE.test(name)}function isValidHeaderValue(value){return value.length>0&&HEADER_VALUE_RE.test(value)}function hasValidHeaderArgs(args){return typeof args=="string"?isValidHeaderValue(args):Array.isArray(args)?args.every(isValidHeaderValue):!1}function applyTransform(data,transform,isHeader){let keySelector=transform.target?.key;if(keySelector==null||isHeader&&(transform.op==="set"||transform.op==="append")&&(typeof keySelector=="string"&&!isValidHeaderName(keySelector)||!hasValidHeaderArgs(transform.args)))return;let matchedKeys=findMatchingKeys(data,keySelector);switch(transform.op){case"set":opSet(data,matchedKeys,keySelector,transform.args);break;case"append":opAppend(data,matchedKeys,keySelector,transform.args,isHeader);break;case"delete":opDelete(data,matchedKeys,transform.args,isHeader);break;default:break}}function isValidRequestPath(path6){if(path6===""||path6.length>2048||path6[0]!=="/"||path6.startsWith("//")||/[?#]/.test(path6))return!1;for(let i=0;i<path6.length;i++){let code=path6.charCodeAt(i);if(code<=32||code===127)return!1}return!0}function getRequestPath(transforms){let path6;for(let transform of transforms)transform.type==="request.path"&&transform.op==="set"&&typeof transform.args=="string"&&isValidRequestPath(transform.args)&&(path6=transform.args);return path6}function findMatchingKeys(data,keyPattern){let matched=[];for(let key of Object.keys(data))matchesRule(key,keyPattern)&&matched.push(key);return matched}function matchesRule(candidate,rule){if(candidate=candidate.toLowerCase(),rule==null)return!0;if(typeof rule=="string")return candidate===rule.toLowerCase();let r=rule;for(let[op,val]of Object.entries(r))if(val!==void 0)switch(op){case"eq":if(candidate!==String(val).toLowerCase())return!1;break;case"neq":if(candidate===val.toLowerCase())return!1;break;case"inc":if(!val.some(v=>candidate===v.toLowerCase()))return!1;break;case"ninc":if(val.some(v=>candidate===v.toLowerCase()))return!1;break;case"pre":if(!candidate.startsWith(String(val).toLowerCase()))return!1;break;case"suf":if(!candidate.endsWith(String(val).toLowerCase()))return!1;break;case"sub":if(!candidate.includes(String(val).toLowerCase()))return!1;break;case"gt":if(!(Number(candidate)>val))return!1;break;case"gte":if(!(Number(candidate)>=val))return!1;break;case"lt":if(!(Number(candidate)<val))return!1;break;case"lte":if(!(Number(candidate)<=val))return!1;break;default:break}return!0}function opSet(data,matchedKeys,keySelector,args){for(let key of matchedKeys)data[key]=args;matchedKeys.length===0&&typeof keySelector=="string"&&data[keySelector]===void 0&&!isEmptyArgs(args)&&(data[keySelector]=args)}function opAppend(data,matchedKeys,keySelector,args,isHeader){if(isEmptyArgs(args))return;let toAppend=typeof args=="string"?[args]:args??[];for(let key of matchedKeys){let next=[...toValueList(data[key],isHeader),...toAppend];setTransformValue(data,key,fromValueList(next))}matchedKeys.length===0&&typeof keySelector=="string"&&setTransformValue(data,keySelector,fromValueList(toAppend))}function opDelete(data,matchedKeys,args,isHeader){if(args==null){for(let key of matchedKeys)delete data[key];return}let patterns=typeof args=="string"?[args]:args;for(let key of matchedKeys){let kept=toValueList(data[key],isHeader).filter(value=>!patterns.some(pattern=>matchesRule(value,pattern)));setTransformValue(data,key,fromValueList(kept))}}function toValueList(value,isHeader){if(value===void 0)return[];if(Array.isArray(value))return value;let str=String(value);return isHeader&&str.includes(",")?str.split(",").map(v=>v.trim()).filter(v=>v!==""):[str]}function fromValueList(values){if(values.length!==0)return values.length===1?values[0]:values}function setTransformValue(data,key,value){value===void 0?delete data[key]:data[key]=value}function isEmptyArgs(args){return args==null?!0:typeof args=="string"?args==="":args.length===0}function resolveRouteParameters(str,match,keys){return str.replace(/\$([1-9a-zA-Z]+)/g,(_,param2)=>{let matchIndex=keys.indexOf(param2);return matchIndex===-1?matchIndex=parseInt(param2,10):matchIndex++,match[matchIndex]||""})}function getRoutesTypes(routes=[]){let handleMap=new Map,prevHandle=null;return routes.forEach(route=>{if((0,import_routing_utils.isHandler)(route))prevHandle=route.handle;else{let routes2=handleMap.get(prevHandle);routes2?routes2.push(route):handleMap.set(prevHandle,[route])}}),handleMap}async function devRouter(reqUrl="/",reqMethod,routes,devServer,vercelConfig,previousHeaders,missRoutes,phase){let result,{pathname:reqPathname,search:reqSearch}=url2.parse(reqUrl);reqPathname=reqPathname||"/";let reqQuery=parseQueryString(reqSearch),combinedHeaders={...previousHeaders},status,isContinue=!1,requestTransforms=[],responseTransforms;if(routes){let idx=-1;for(let routeConfig of routes){if(idx++,isContinue=!1,(0,import_routing_utils.isHandler)(routeConfig))continue;let{src,headers,methods}=routeConfig;if(Array.isArray(methods)&&reqMethod&&!methods.includes(reqMethod))continue;let keys=[],flags=devServer&&devServer.isCaseSensitive()?"":"i",matcher=(0,import_pcre_to_regexp.default)(`%${src}%${flags}`,keys),match=matcher.exec(reqPathname)||matcher.exec(reqPathname.substring(1));if(match){let routeTransforms=routeConfig.transforms?resolveTransforms(routeConfig.transforms,{match,keys,env:devServer?.envConfigs.runEnv}):[],isServiceMarker=typeof routeConfig.destination=="object"&&routeConfig.destination!==null&&routeConfig.destination.type==="service";!isServiceMarker&&routeTransforms.length>0&&requestTransforms.push(...routeTransforms);let destPath=reqPathname;if(routeConfig.dest&&(destPath=resolveRouteParameters(routeConfig.dest,match,keys)),headers)for(let originalKey of Object.keys(headers)){let lowerKey=originalKey.toLowerCase();if(!(previousHeaders&&Object.prototype.hasOwnProperty.call(previousHeaders,lowerKey)&&(phase==="hit"||phase==="miss"))){let originalValue=headers[originalKey],value=resolveRouteParameters(originalValue,match,keys);combinedHeaders[lowerKey]=value}}if(routeConfig.continue){routeConfig.status&&(status=routeConfig.status),routeTransforms.length>0&&(responseTransforms=routeTransforms),reqPathname=destPath,isContinue=!0;continue}let isDestUrl=isURL(destPath);if(routeConfig.check&&devServer&&vercelConfig&&phase!=="hit"&&!isDestUrl){let{pathname}=url2.parse(destPath);if(pathname=pathname||"/",!await devServer.hasFilesystem(pathname,vercelConfig)&&!(routeConfig.status&&phase!=="miss"))if(missRoutes&&missRoutes.length>0){routeTransforms.length>0&&(responseTransforms=routeTransforms);let missResult=await devRouter(destPath,reqMethod,missRoutes,devServer,vercelConfig,combinedHeaders,[],"miss");if(missResult.found)return requestTransforms.length>0&&(missResult.requestTransforms=[...requestTransforms,...missResult.requestTransforms??[]]),!missResult.responseTransforms&&responseTransforms&&(missResult.responseTransforms=responseTransforms),missResult;reqPathname=destPath;continue}else{routeConfig.status&&phase==="miss"&&(status=routeConfig.status),routeTransforms.length>0&&(responseTransforms=routeTransforms),reqPathname=destPath;continue}}let effectiveStatus=routeConfig.status||status,isRedirectExit=typeof effectiveStatus=="number"&&effectiveStatus>=300&&effectiveStatus<400;if(!isServiceMarker&&!isRedirectExit&&routeTransforms.length>0&&(responseTransforms=routeTransforms),isDestUrl){result={found:!0,dest:destPath,continue:isContinue,userDest:!1,isDestUrl,status:routeConfig.status||status,headers:combinedHeaders,query:reqQuery,matched_route:routeConfig,matched_route_idx:idx,phase,requestTransforms,responseTransforms};break}else{destPath.startsWith("/")||(destPath=`/${destPath}`);let{pathname:destPathname,search:destSearch}=url2.parse(destPath);destPathname=destPathname||"/";let destQuery=parseQueryString(destSearch);Object.assign(destQuery,reqQuery),result={found:!0,dest:destPathname,continue:isContinue,userDest:!!routeConfig.dest,isDestUrl,status:routeConfig.status||status,headers:combinedHeaders,query:destQuery,matched_route:routeConfig,matched_route_idx:idx,phase,requestTransforms,responseTransforms};break}}}}return result||(result={found:!1,dest:reqPathname,continue:isContinue,status,isDestUrl:!1,query:reqQuery,headers:combinedHeaders,phase,requestTransforms,responseTransforms}),result}var import_mime_types=__toESM(require_mime_types(),1);import path from"path";function getMimeType(fileName){let extension=path.extname(fileName);return(0,import_mime_types.contentType)(extension)||"application/octet-stream"}var import_ms2=__toESM(require_ms(),1),import_bytes=__toESM(require_bytes(),1),import_build_utils3=__toESM(require_build_utils(),1),import_fs_detectors=__toESM(require_dist4(),1),import_pluralize=__toESM(require_pluralize(),1),import_minimatch=__toESM(require_minimatch(),1);import{readFileSync,unlinkSync}from"fs";import{delimiter,dirname,join}from"path";import{fork}from"child_process";import{createFunction}from"@vercel/fun";var import_tree_kill=__toESM(require_tree_kill(),1);function treeKill(pid,signal="SIGTERM"){return new Promise((resolve3,reject)=>{(0,import_tree_kill.default)(pid,signal,err=>{err?reject(err):resolve3()})})}var import_routing_utils2=__toESM(require_dist3(),1);async function getUnsupportedBuilderVersionError(version){let updateMessage;try{updateMessage=`Please run \`${await getUpdateCommand()}\` to update to the latest CLI.`}catch(error2){updateMessage=error2 instanceof Error?error2.message:"Update the CLI with the package manager that installed it."}return dev.DEV_UNSUPPORTED_BUILDER_VERSION({titleName:getTitleName(),version,updateMessage})}async function deserializeOutput(obj){switch(obj.type){case"FileFsRef":return Object.assign(Object.create(import_build_utils3.FileFsRef.prototype),obj);case"FileBlob":{let fileBlob=Object.assign(Object.create(import_build_utils3.FileBlob.prototype),obj);return fileBlob.data=Buffer.from(obj.data.data),fileBlob}case"Lambda":{let lambda=Object.assign(Object.create(import_build_utils3.Lambda.prototype),obj);if(obj.zipBufferPath){lambda.zipBuffer=readFileSync(obj.zipBufferPath);try{unlinkSync(obj.zipBufferPath)}catch{}}else obj.zipBuffer&&(lambda.zipBuffer=Buffer.from(obj.zipBuffer.data));return lambda}}}async function deserializeBuildOutputs(serialized){let result={};for(let[name,obj]of Object.entries(serialized))result[name]=await deserializeOutput(obj);return result}async function createBuildProcess(match,envConfigs,workPath){output_manager_default.debug(`Creating build process for "${match.entrypoint}"`);let builderWorkerPath=join(__dirname,"builder-worker.cjs"),nodeExecPath=(0,import_build_utils3.getNodeExecPath)(),PATH=`${dirname(nodeExecPath)}${delimiter}${process.env.PATH}`,env={...process.env,PATH,...envConfigs.allEnv},buildProcess=fork(builderWorkerPath,[],{cwd:workPath,execArgv:[],execPath:isNativeBinaryInstall()?process.execPath:nodeExecPath,env});return match.buildProcess=buildProcess,buildProcess.on("close",(code,signal)=>{output_manager_default.debug(`Build process for "${match.entrypoint}" exited with ${signal||code}`),match.buildProcess=void 0}),new Promise((resolve3,reject)=>{buildProcess.once("message",data=>{data!==null&&typeof data=="object"&&data.type!=="ready"?reject(new Error('Did not get "ready" event from builder')):resolve3(buildProcess)})})}async function executeBuild(vercelConfig,devServer,files,match,requestPath,isInitialBuild,filesChanged,filesRemoved){let{builderWithPkg:{path:requirePath,builder,pkg}}=match,{entrypoint,use}=match,isStatic=(0,import_fs_detectors.isStaticRuntime)(use),{envConfigs,cwd:workPath,devCacheDir}=devServer,debug=output_manager_default.isDebugEnabled(),startTime=Date.now(),showBuildTimestamp=!isStatic&&(!isInitialBuild||debug);showBuildTimestamp&&(output_manager_default.log(`Building ${use}:${entrypoint}`),output_manager_default.debug(`Using \`${pkg.name}${pkg.version?`@${pkg.version}`:""}\``));let config=match.config||{},result,{buildProcess}=match;!isStatic&&!buildProcess&&(buildProcess=await createBuildProcess(match,envConfigs,workPath));let serviceRoutePrefix=config.routePrefix,serviceWorkspace=config.workspace,buildOptions={files,entrypoint,workPath,repoRootPath:workPath,config,meta:{isDev:!0,requestPath,devCacheDir,filesChanged,filesRemoved,env:{...envConfigs.runEnv},buildEnv:{...envConfigs.buildEnv}},...typeof serviceRoutePrefix=="string"||typeof serviceWorkspace=="string"?{service:{routePrefix:typeof serviceRoutePrefix=="string"?serviceRoutePrefix:void 0,workspace:typeof serviceWorkspace=="string"?serviceWorkspace:void 0}}:void 0},buildResultOrOutputs;buildProcess?(buildProcess.send({type:"build",requirePath,buildOptions}),buildResultOrOutputs=await new Promise((resolve3,reject)=>{function onMessage({type,result:result2,error:error2}){cleanup(),type==="buildResult"?result2?resolve3(result2):error2&&reject(Object.assign(new Error,error2)):reject(new Error(`Got unexpected message type: ${type}`))}function onExit(code,signal){cleanup();let err=new Error(`Builder exited with ${signal||code} before sending build result`);reject(err)}function cleanup(){buildProcess.removeListener("close",onExit),buildProcess.removeListener("message",onMessage)}buildProcess.on("close",onExit),buildProcess.on("message",onMessage)})):buildResultOrOutputs=await builder.build(buildOptions);let effectiveVersion=builder.version;if(effectiveVersion===-1)if("resultVersion"in buildResultOrOutputs){let vx=buildResultOrOutputs;effectiveVersion=vx.resultVersion,buildResultOrOutputs=vx.result}else effectiveVersion=buildResultOrOutputs.output?.type==="Lambda"?3:2;if(!effectiveVersion||effectiveVersion===1)result={output:buildResultOrOutputs,routes:[],watch:[]};else if(effectiveVersion===2)result=buildResultOrOutputs;else if(effectiveVersion===3){let{output,...rest}=buildResultOrOutputs;if(!output||output.type!=="Lambda")throw dev.DEV_BUILDER_RESULT_NOT_LAMBDA();if(output.maxDuration)throw dev.DEV_BUILDER_RESULT_HAS_MAXDURATION();if(output.affinity)throw new Error('The result of "builder.build()" must not contain `affinity`');if(output.maxConcurrency)throw new Error('The result of "builder.build()" must not contain `maxConcurrency`');if(output.memory)throw dev.DEV_BUILDER_RESULT_HAS_MEMORY();for(let[src,func]of Object.entries(config.functions||{}))if(src===entrypoint||(0,import_minimatch.default)(entrypoint,src)){func.maxDuration&&(output.maxDuration=func.maxDuration),func.affinity&&(output.affinity=func.affinity),func.maxConcurrency&&(output.maxConcurrency=func.maxConcurrency),func.memory&&(output.memory=func.memory);break}result={...rest,output:{[entrypoint]:output}}}else throw await getUnsupportedBuilderVersionError(builder.version);let normalized=(0,import_routing_utils2.normalizeRoutes)(result.routes);if(normalized.error)throw dev.DEV_INVALID_ROUTES({message:normalized.error.message});result.routes=normalized.routes||[];let{output:buildOutput}=result,{cleanUrls}=vercelConfig;for(let[originalPath,value]of Object.entries(buildOutput)){let path6=(0,import_build_utils3.normalizePath)(originalPath);cleanUrls&&path6.endsWith(".html")&&(path6=path6.slice(0,-5),(value.type==="FileBlob"||value.type==="FileFsRef")&&(value.contentType=value.contentType||"text/html; charset=utf-8"));let extensionless=devServer.getExtensionlessFile(path6);extensionless&&(path6=extensionless),buildOutput[path6]=value}let deserializedOutput=await deserializeBuildOutputs(buildOutput);for(let[name,output]of Object.entries(deserializedOutput))buildOutput[name]=output;result.watch=(result.watch||[]).map(w=>w.startsWith("./")?w.substring(2):w),result.watch.includes(entrypoint)||result.watch.push(entrypoint);let maxLambdaBytes=(0,import_bytes.default)("50mb");for(let asset of Object.values(result.output))if(asset.type==="Lambda"&&!(typeof asset.runtime=="string"&&asset.runtime.startsWith("python"))&&asset.runtime!=="container"){let size=asset.zipBuffer.length;if(size>maxLambdaBytes)throw new LambdaSizeExceededError(size,maxLambdaBytes)}if(await Promise.all(Object.entries(result.output).map(async entry=>{let path6=entry[0],asset=entry[1];if(asset.type==="Lambda"&&asset.runtime!=="container"){let oldAsset=match.buildOutput&&match.buildOutput[path6];oldAsset&&oldAsset.type==="Lambda"&&oldAsset.fn&&await oldAsset.fn.destroy();let ZipFile=asset.zipBuffer||await asset.createZip();asset.fn=await createFunction({Code:{ZipFile},Handler:asset.handler,Runtime:asset.runtime,MemorySize:asset.memory||3009,Environment:{Variables:{...vercelConfig.env,...asset.environment,...envConfigs.runEnv}}})}match.buildTimestamp=Date.now()})),match.buildResultVersion=effectiveVersion,match.buildResults.set(requestPath,result),Object.assign(match.buildOutput,result.output),showBuildTimestamp){let endTime=Date.now();output_manager_default.log(`Built ${use}:${entrypoint} [${(0,import_ms2.default)(endTime-startTime)}]`)}}async function getBuildMatches(vercelConfig,cwd,devServer,fileList){let matches=[];if(fileList.length===0)return matches;let noMatches=[],builds=vercelConfig.builds||[{src:"**",use:"@vercel/static"}],builderSpecs=new Set(builds.map(b=>b.use).filter(Boolean)),buildersWithPkgs=await importBuilders(builderSpecs,cwd);for(let buildConfig of builds){let{src="**",use,config={}}=buildConfig;if(!use)continue;src[0]==="/"&&(src=src.substring(1)),(0,import_build_utils3.isBackendFramework)(buildConfig.config?.framework)&&(src="package.json");let mapToEntrypoint=new Map;if(buildConfig.config?.framework&&(0,import_build_utils3.isPythonFramework)(buildConfig.config?.framework)){let originalSrc=src,existing=["pyproject.toml","requirements.txt","Pipfile"].filter(p=>fileList.includes(p));existing.length>0&&(src=existing[0],mapToEntrypoint.set(src,originalSrc))}if(buildConfig.config?.framework==="node"&&!fileList.includes(src)){let originalSrc=src,existing=fileList.find(path6=>/^(?:src\/)?server\.[cm]?[jt]s$/.test(path6));existing&&(src=existing,mapToEntrypoint.set(src,originalSrc))}if(buildConfig.config?.framework==="go"&&!fileList.includes(src)){let originalSrc=src,existing=["main.go","cmd/api/main.go","cmd/server/main.go"].filter(p=>fileList.includes(p));existing.length>0&&(src=existing[0],mapToEntrypoint.set(src,originalSrc))}if(buildConfig.config?.framework==="rust"&&src==="src/main.rs"&&!fileList.includes(src)){let originalSrc=src;fileList.includes("Cargo.toml")&&(src="Cargo.toml",mapToEntrypoint.set(src,originalSrc))}if(buildConfig.config?.framework==="container"&&!fileList.includes(src)){let originalSrc=src,existing=["Dockerfile.vercel","Containerfile.vercel","Dockerfile","Containerfile"].find(p=>fileList.includes(p));existing&&(src=existing,mapToEntrypoint.set(src,originalSrc))}let extensionless=devServer.getExtensionlessFile(src);extensionless&&(mapToEntrypoint.set(extensionless,src),src=extensionless);let files=fileList.filter(name=>name===src||(0,import_minimatch.default)(name,src,{dot:!0})).map(name=>join(cwd,name));files.length===0&&(config.zeroConfig&&use==="@vercel/static"||noMatches.push(buildConfig));for(let file of files){src=relative(cwd,file);let entrypoint=mapToEntrypoint.get(src)||src;if(config.zeroConfig&&config.outputDirectory){let outputMatch=config.outputDirectory+"/";src.startsWith(outputMatch)&&(src=src.slice(outputMatch.length))}let builderWithPkg=buildersWithPkgs.get(use);if(!builderWithPkg)throw dev.DEV_BUILDER_LOAD_FAILED({use});matches.push({...buildConfig,src,entrypoint,builderWithPkg,buildOutput:{},buildResults:new Map,buildTimestamp:0})}}if(noMatches.length>0){output_manager_default.warn(`You defined ${(0,import_pluralize.default)("build",noMatches.length,!0)} that did not match any source files (please ensure they are NOT defined in ${highlight(".vercelignore")}):`);for(let buildConfig of noMatches)output_manager_default.print(`- ${JSON.stringify(buildConfig)}
|
|
23
|
-
`)}return matches}async function shutdownBuilder(match){let ops=[];if(match.buildProcess){let{pid}=match.buildProcess;output_manager_default.debug(`Killing builder sub-process with PID ${pid}`);let killPromise=treeKill(pid).then(()=>{output_manager_default.debug(`Killed builder with PID ${pid}`)}).catch(err=>{output_manager_default.debug(`Failed to kill builder with PID ${pid}: ${err}`)});ops.push(killPromise),delete match.buildProcess}if(match.buildOutput)for(let asset of Object.values(match.buildOutput))asset.type==="Lambda"&&asset.fn&&(output_manager_default.debug("Shutting down Lambda function"),ops.push(asset.fn.destroy()));await Promise.all(ops)}var import_build_utils4=__toESM(require_build_utils(),1),import_frameworks=__toESM(require_frameworks(),1);var BUILDPACK_DEV_UNSUPPORTED="BUILDPACK_DEV_UNSUPPORTED";function getBuildpackRuntime(builder){let buildpack=builder?.config?.buildpack;return typeof buildpack=="string"&&buildpack.length>0?buildpack:void 0}function runtimeDisplayName(runtime){return import_frameworks.frameworkList.find(f=>f.slug===runtime)?.name??runtime}function buildpackDevUnsupportedError(runtime){return new import_build_utils4.NowBuildError({code:BUILDPACK_DEV_UNSUPPORTED,message:`${getCommandName("dev")} doesn't support ${runtimeDisplayName(runtime)} projects yet.`})}function buildpackServicesDevUnsupportedError(services){let names=services.map(s=>`"${s.name}"`),list=names.length===1?names[0]:`${names.slice(0,-1).join(", ")} and ${names[names.length-1]}`,label=`${[...new Set(services.map(s=>runtimeDisplayName(s.runtime)))].join(" and ")} ${names.length===1?"service":"services"}`;return new import_build_utils4.NowBuildError({code:BUILDPACK_DEV_UNSUPPORTED,message:`${getCommandName("dev")} doesn't support the ${label} ${list} yet.`})}function assertNoBuildpackServices(services){let blocked=[];for(let service of services){let runtime=getBuildpackRuntime(service.builder);runtime&&blocked.push({name:service.name,runtime})}if(blocked.length>0)throw buildpackServicesDevUnsupportedError(blocked)}var httpStatusDescriptionMap=new Map([[400,"BAD_REQUEST"],[402,"PAYMENT_REQUIRED"],[403,"FORBIDDEN"],[404,"NOT_FOUND"],[405,"NOT_ALLOWED"],[410,"GONE"],[413,"PAYLOAD_TOO_LARGE"],[429,"RATE_LIMITED"],[500,"INTERNAL_SERVER_ERROR"],[501,"NOT_IMPLEMENTED"],[502,"BAD_GATEWAY"],[503,"SERVICE_UNAVAILABLE"],[504,"GATEWAY_TIMEOUT"],[508,"INFINITE_LOOP"]]),errorMessageMap=new Map([[400,"Bad request"],[402,"Payment required"],[403,"You don't have the required permissions"],[404,"The page could not be found"],[405,"Method not allowed"],[410,"The deployment has been removed"],[413,"Request Entity Too Large"],[429,"Rate limited"],[500,"A server error has occurred"],[501,"Not implemented"],[503,"The deployment is currently unavailable"],[504,"An error occurred with your deployment"],[508,"Infinite loop detected"]]),appError={title:"An error occurred with this application.",subtitle:"This is an error with the application itself, not the platform.",app_error:!0},pageNotFoundError={title:"The page could not be found.",subtitle:"The page could not be found in the application.",app_error:!0};function generateErrorMessage(statusCode,errorCode){return statusCode===404?pageNotFoundError:statusCode===502?appError:{title:errorMessageMap.get(statusCode)||"Error occurred",app_error:!1}}function generateHttpStatusDescription(statusCode){return httpStatusDescriptionMap.get(statusCode)||"UNKNOWN_ERROR"}function createErrorReporter2(recordCode){return createErrorReporter(recordCode,toDiagnostic2,telemetryCodes)}var import_escape_html=__toESM(require_escape_html(),1);function error(it){let out="<main> ";return it.error_code=="EDGE_FUNCTION_INVOCATION_FAILED"&&(out+=' <p class="error-title error-title-guilty"> <strong>This Edge Function</strong><span> has crashed.</span> </p> '),out+=" ",it.error_code=="FUNCTION_INVOCATION_FAILED"&&(out+=' <p class="error-title error-title-guilty"> <strong>This Serverless Function</strong><span> has crashed.</span> </p> '),out+=' <p class="devinfo-container"> <span class="error-code"><strong>'+it.http_status_code+"</strong>: "+(0,import_escape_html.default)(it.http_status_description)+"</span> ",it.error_code&&(out+=' <span class="devinfo-line">Code: <code>'+(0,import_escape_html.default)(it.error_code)+"</code></span> "),out+=' <span class="devinfo-line">ID: <code>'+(0,import_escape_html.default)(it.request_id)+"</code> </p> <p> <ul> <li> Check the logs in your terminal window to see the application error. </li> </ul> </p></main>",out}var import_escape_html2=__toESM(require_escape_html(),1);function error_base(it){return'<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="theme-color" content="#000"> <title>'+it.http_status_code+": "+(0,import_escape_html2.default)(it.http_status_description)+`</title> <style> html { font-size: 62.5%; box-sizing: border-box; height: -webkit-fill-available } *, ::after, ::before { box-sizing: inherit } body { font-family: "SF Pro Text", "SF Pro Icons", "Helvetica Neue", "Helvetica", "Arial", sans-serif; font-size: 1.6rem; line-height: 1.65; word-break: break-word; font-kerning: auto; font-variant: normal; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-rendering: optimizeLegibility; hyphens: auto; height: 100vh; height: -webkit-fill-available; max-height: 100vh; max-height: -webkit-fill-available; margin: 0 } ::selection { background: #79FFE1; } ::-moz-selection { background: #79FFE1; } a { cursor: pointer; color: #0070f3; text-decoration: none; transition: all .2s ease; border-bottom: 1px solid transparent } a:hover { border-bottom: 1px solid #0070f3 } ul { padding: 0; margin-left: 1.5em; list-style-type: none } li { margin-bottom: 10px } ul li:before { content: '\\02013' } li:before { display: inline-block; color: #ccc; position: absolute; margin-left: -18px; transition: color .2s ease } code { font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif; font-size: .92em } code:after, code:before { content: '\`' } .container { display: flex; justify-content: center; flex-direction: column; min-height: 100% } main { max-width: 80rem; padding: 4rem 6rem; margin: auto } ul { margin-bottom: 32px } .error-title { font-size: 2rem; padding-left: 22px; line-height: 1.5; margin-bottom: 24px; } .error-title-guilty { border-left: 2px solid #ED367F; } .error-title-innocent { border-left: 2px solid #59B89C; } main p { color: #333 } .devinfo-container { border: 1px solid #ddd; border-radius: 4px; padding: 2rem; display: flex; flex-direction: column; margin-bottom: 32px } .error-code { margin: 0; font-size: 1.6rem; color: #000; margin-bottom: 1.6rem } .devinfo-line { color: #333 } .devinfo-line code, code, li { color: #000 } .devinfo-line:not(:last-child) { margin-bottom: 8px } .docs-link, .contact-link { font-weight: 500 } header, footer, footer a { display: flex; justify-content: center; align-items: center } header, footer { min-height: 100px; height: 100px; } header { border-bottom: 1px solid #eaeaea; } header h1 { font-size: 1.8rem; margin: 0; font-weight: 500; } header p { font-size: 1.3rem; margin: 0; font-weight: 500; } .header-item { display: flex; padding: 0 2rem; margin: 2rem 0; text-decoration: line-through; color: #999; } .header-item.active { color: #ff0080; text-decoration: none; } .header-item.first { border-right: 1px solid #eaeaea; } .header-item-content { display: flex; flex-direction: column; } .header-item-icon { margin-right: 1rem; margin-top: 0.6rem; } footer { border-top: 1px solid #eaeaea; } footer a { color: #000 } footer a:hover { border-bottom-color: transparent } footer svg { margin-left: .8rem } .note { padding: 8pt 16pt; border-radius: 5px; border: 1px solid #0070f3; font-size: 14px; line-height: 1.8; color: #0070f3; } @media (max-width:500px) { .devinfo-container .devinfo-line code { margin-top: .4rem } .devinfo-container .devinfo-line:not(:last-child) { margin-bottom: 1.6rem } .devinfo-container { margin-bottom: 0; } header { flex-direction: column; height: auto; min-height: auto; align-items: flex-start; } .header-item.first { border-right: none; margin-bottom: 0; } main { padding: 1rem 2rem; } body { font-size: 1.4rem; line-height: 1.55; } footer { display: none; } .note { margin-top: 16px; } } </style> </head> <body> <div class="container"> `+it.view+" </div> </body></html>"}var import_escape_html3=__toESM(require_escape_html(),1);function error_404(it){let out='<main> <p class="devinfo-container"> <span class="error-code"><strong>'+it.http_status_code+"</strong>: "+(0,import_escape_html3.default)(it.http_status_description)+"</span> ";return it.error_code&&(out+=' <span class="devinfo-line">Code: <code>'+(0,import_escape_html3.default)(it.error_code)+"</code></span> "),out+=' <span class="devinfo-line">ID: <code>'+(0,import_escape_html3.default)(it.request_id)+"</code> </p></main>",out}var import_escape_html4=__toESM(require_escape_html(),1);function error_502(it){let out='<main> <p class="devinfo-container"> <span class="error-code"><strong>'+it.http_status_code+"</strong>: "+(0,import_escape_html4.default)(it.http_status_description)+"</span> ";return it.error_code&&(out+=' <span class="devinfo-line">Code: <code>'+(0,import_escape_html4.default)(it.error_code)+"</code></span> "),out+=' <span class="devinfo-line">ID: <code>'+(0,import_escape_html4.default)(it.request_id)+"</code> </p> <p> <ul> <li> Check the logs in your terminal window to see the application error. </li> </ul> </p></main>",out}var import_escape_html5=__toESM(require_escape_html(),1);function redirect(it){return"<!doctype html><!-- https://now.sh --><h1>Redirecting ("+it.statusCode+")</h1><a>"+(0,import_escape_html5.default)(it.location)+"</a>"}var import_ms4=__toESM(require_ms(),1),import_get_port=__toESM(require_get_port(),1),import_chalk=__toESM(require_source(),1),import_frameworks2=__toESM(require_frameworks(),1);import path2 from"path";import{Transform,Writable}from"stream";function parseCronFields(expression){let parts=expression.trim().split(/\s+/);if(parts.length!==5)return null;let[minute,hour,dayOfMonth,month,dayOfWeek]=parts;return{minute,hour,dayOfMonth,month,dayOfWeek}}function expandCronField(field,min,max){let values=new Set;for(let part of field.split(",")){let stepMatch=part.match(/^(.+)\/(\d+)$/),range=stepMatch?stepMatch[1]:part,step=stepMatch?parseInt(stepMatch[2],10):1,start,end;if(range==="*")start=min,end=max;else if(range.includes("-")){let[lo,hi]=range.split("-").map(Number);start=lo,end=hi}else{let val=parseInt(range,10);start=val,end=val}for(let i=start;i<=end;i+=step)values.add(i)}return values}function nextOrWrap(sorted,current){for(let v of sorted)if(v>=current)return v;return null}function dayMatches(date,daysOfMonth,daysOfWeek,orDays){return orDays?daysOfMonth.has(date.getDate())||daysOfWeek.has(date.getDay()):daysOfMonth.has(date.getDate())&&daysOfWeek.has(date.getDay())}function getNextCronDelay(expression,now=new Date){let parsed=parseCronFields(expression);if(!parsed)return null;let minuteSet=expandCronField(parsed.minute,0,59),hourSet=expandCronField(parsed.hour,0,23),domSet=expandCronField(parsed.dayOfMonth,1,31),monthSet=expandCronField(parsed.month,1,12),dowSet=expandCronField(parsed.dayOfWeek,0,6),sortedMinutes=[...minuteSet].sort((a,b)=>a-b),sortedHours=[...hourSet].sort((a,b)=>a-b),sortedMonths=[...monthSet].sort((a,b)=>a-b),orDays=parsed.dayOfMonth!=="*"&&parsed.dayOfWeek!=="*",t=new Date(now);t.setSeconds(0,0),t.setMinutes(t.getMinutes()+1);let maxYear=t.getFullYear()+4;for(;t.getFullYear()<=maxYear;){let month=t.getMonth()+1,nextMonth=nextOrWrap(sortedMonths,month);if(nextMonth===null||nextMonth>month){let targetMonth=nextMonth??sortedMonths[0];nextMonth===null&&t.setFullYear(t.getFullYear()+1),t.setMonth(targetMonth-1,1),t.setHours(sortedHours[0],sortedMinutes[0]);continue}if(!dayMatches(t,domSet,dowSet,orDays)){t.setDate(t.getDate()+1),t.setHours(sortedHours[0],sortedMinutes[0]);continue}let hour=t.getHours(),nextHour=nextOrWrap(sortedHours,hour);if(nextHour===null||nextHour>hour){nextHour===null?(t.setDate(t.getDate()+1),t.setHours(sortedHours[0],sortedMinutes[0])):t.setHours(nextHour,sortedMinutes[0]);continue}let minute=t.getMinutes(),nextMinute=nextOrWrap(sortedMinutes,minute);if(nextMinute===null||nextMinute>minute){nextMinute===null?t.setHours(t.getHours()+1,sortedMinutes[0]):t.setMinutes(nextMinute);continue}return t.getTime()-now.getTime()}return null}var import_build_utils5=__toESM(require_build_utils(),1);var import_service_schedules=__toESM(require_service_schedules(),1);import{chmodSync,mkdirSync,readFileSync as readFileSync2,renameSync,rmSync,writeFileSync}from"node:fs";import{randomUUID}from"node:crypto";import{dirname as dirname2,isAbsolute,join as join2,normalize,sep}from"node:path";var manifest_default={nextDevWebSocketPreload:{source:"node-preloads/next-dev-websocket.cjs",destination:"node-preloads/next-dev-websocket.cjs"}};var runtimeAssets=manifest_default;function getRuntimeAssetsDir(version=pkg_default.version,globalRoot=getGlobalPathConfig()){return join2(globalRoot,"runtime-assets",version)}function materializeRuntimeAsset(id,options={}){let definition2=runtimeAssets[id];if(!definition2)throw new Error(`Unknown runtime asset: ${String(id)}`);let source=validateRelativePath(id,"source",definition2.source),destination=validateRelativePath(id,"destination",definition2.destination),data=readRuntimeAsset(source),destinationPath=join2(getRuntimeAssetsDir(options.version??pkg_default.version,options.globalRoot??getGlobalPathConfig()),destination),destinationDir=dirname2(destinationPath),temporaryPath=`${destinationPath}.${process.pid}.${randomUUID()}.tmp`;mkdirSync(destinationDir,{recursive:!0});try{writeFileSync(temporaryPath,new Uint8Array(data.buffer,data.byteOffset,data.byteLength)),definition2.executable&&chmodSync(temporaryPath,493);try{renameSync(temporaryPath,destinationPath)}catch(error2){let code=error2.code;if(code!=="EEXIST"&&code!=="EPERM")throw error2;rmSync(destinationPath,{force:!0}),renameSync(temporaryPath,destinationPath)}}finally{rmSync(temporaryPath,{force:!0})}return destinationPath}function readRuntimeAsset(source,moduleDir=__dirname){let candidates=[join2(moduleDir,"runtime-assets",source),join2(moduleDir,"..","runtime-assets",source),join2(moduleDir,"..","..","runtime-assets",source)],lastError;for(let candidate of candidates)try{return readFileSync2(candidate)}catch(error2){if(error2.code!=="ENOENT")throw error2;lastError=error2}throw lastError}function validateRelativePath(id,field,value){let normalized=normalize(value);if(!value||isAbsolute(value)||normalized===".."||normalized.startsWith(`..${sep}`))throw new Error(`Runtime asset "${id}" has an invalid ${field} path: ${JSON.stringify(value)}`);return normalized}function injectNextDevWebSocketShimIfNeeded(env,command,projectSettings,runtimeOptions){if(!shouldInjectNextDevWebSocketShim(command,projectSettings))return;let shimPath=materializeRuntimeAsset("nextDevWebSocketPreload",runtimeOptions);return env.NODE_OPTIONS=prependNodeRequireOption(env.NODE_OPTIONS,shimPath),shimPath}function shouldInjectNextDevWebSocketShim(command,projectSettings){return projectSettings?.framework==="nextjs"||/(?:^|\s)(?:next|next\.js)(?:\s+dev)?(?:\s+-|\s*$|$)/.test(command)}function prependNodeRequireOption(nodeOptions,requirePath){let requireOption=`--require ${JSON.stringify(requirePath)}`;return nodeOptions?`${requireOption} ${nodeOptions}`:requireOption}function replaceDevCommandPort(command,port){return command.replace(/\$PORT/g,`${port}`).replace(/%PORT%/g,`${port}`)}var import_ms3=__toESM(require_ms(),1);var DEV_RUNTIME_CACHE_PREFIX="/_svc/_cache/",DEV_RUNTIME_CACHE_API_PREFIX="/v1/suspense-cache/",DEV_RUNTIME_CACHE_ITEM_PREFIX=`${DEV_RUNTIME_CACHE_PREFIX}v1/suspense-cache/`,HEADER_CACHE_STATE="x-vercel-cache-state",HEADER_CACHE_TAGS="x-vercel-cache-tags",HEADER_REVALIDATE="x-vercel-revalidate",HEADER_CACHE_ITEM_NAME="x-vercel-cache-item-name",TICK_INTERVAL=(0,import_ms3.default)("1m");function getDevRuntimeCacheEnv(origin,itemPrefix=DEV_RUNTIME_CACHE_ITEM_PREFIX){return{RUNTIME_CACHE_ENDPOINT:`${origin}${itemPrefix}`,RUNTIME_CACHE_HEADERS:JSON.stringify({authorization:`Bearer ${DEV_RESOURCE_TOKEN}`})}}var RuntimeCacheStore=class{constructor(){this.entries=new Map;this.tagExpirations=new Map;this.sequence=0;this.tickTimer=setInterval(()=>this.tick(),TICK_INTERVAL),this.tickTimer.unref()}get(key){let entry=this.entries.get(key);return entry?this.isStale(entry)?(this.entries.delete(key),null):{value:entry.value,tags:entry.tags,ageSeconds:Math.floor((Date.now()-entry.lastModified)/1e3)}:null}set(key,value,options={}){let ttlSeconds=options.ttlSeconds;this.entries.set(key,{value,tags:options.tags??[],ttlMs:ttlSeconds&&ttlSeconds>0?ttlSeconds*1e3:null,lastModified:Date.now(),sequence:++this.sequence})}delete(key){this.entries.delete(key)}expireTags(tags){let sequence=++this.sequence;for(let tag of tags)this.tagExpirations.set(tag,sequence)}size(){return this.entries.size}stop(){clearInterval(this.tickTimer)}isStale(entry){if(entry.ttlMs!==null&&entry.lastModified+entry.ttlMs<=Date.now())return!0;for(let tag of entry.tags){let expiredAt=this.tagExpirations.get(tag);if(expiredAt!==void 0&&expiredAt>entry.sequence)return!0}return!1}tick(){for(let[key,entry]of this.entries)this.isStale(entry)&&this.entries.delete(key)}};var STARTUP_TIMEOUT=(0,import_ms4.default)("5m"),SERVICE_COLORS=[import_chalk.default.cyan,import_chalk.default.magenta,import_chalk.default.yellow,import_chalk.default.green,import_chalk.default.blue];function createServiceLogger(serviceName,colorIndex,maxNameLength){let color=SERVICE_COLORS[colorIndex%SERVICE_COLORS.length],padding=" ".repeat(maxNameLength-serviceName.length),prefix=color(`[${serviceName}]`)+padding,createTransform=streamLabel=>{let buffer="",labelPrefix=output_manager_default.debugEnabled?`${prefix} ${import_chalk.default.gray(`(${streamLabel})`)}`:prefix;return new Transform({transform(chunk,_encoding,callback){buffer+=chunk.toString();let lines=buffer.split(`
|
|
23
|
+
`)}return matches}async function shutdownBuilder(match){let ops=[];if(match.buildProcess){let{pid}=match.buildProcess;output_manager_default.debug(`Killing builder sub-process with PID ${pid}`);let killPromise=treeKill(pid).then(()=>{output_manager_default.debug(`Killed builder with PID ${pid}`)}).catch(err=>{output_manager_default.debug(`Failed to kill builder with PID ${pid}: ${err}`)});ops.push(killPromise),delete match.buildProcess}if(match.buildOutput)for(let asset of Object.values(match.buildOutput))asset.type==="Lambda"&&asset.fn&&(output_manager_default.debug("Shutting down Lambda function"),ops.push(asset.fn.destroy()));await Promise.all(ops)}var import_build_utils4=__toESM(require_build_utils(),1),import_frameworks=__toESM(require_frameworks(),1);var BUILDPACK_DEV_UNSUPPORTED="BUILDPACK_DEV_UNSUPPORTED";function getBuildpackRuntime(builder){let buildpack=builder?.config?.buildpack;return typeof buildpack=="string"&&buildpack.length>0?buildpack:void 0}function runtimeDisplayName(runtime){return import_frameworks.frameworkList.find(f=>f.slug===runtime)?.name??runtime}function buildpackDevUnsupportedError(runtime){return new import_build_utils4.NowBuildError({code:BUILDPACK_DEV_UNSUPPORTED,message:`${getCommandName("dev")} doesn't support ${runtimeDisplayName(runtime)} projects yet.`})}function buildpackServicesDevUnsupportedError(services){let names=services.map(s=>`"${s.name}"`),list=names.length===1?names[0]:`${names.slice(0,-1).join(", ")} and ${names[names.length-1]}`,label=`${[...new Set(services.map(s=>runtimeDisplayName(s.runtime)))].join(" and ")} ${names.length===1?"service":"services"}`;return new import_build_utils4.NowBuildError({code:BUILDPACK_DEV_UNSUPPORTED,message:`${getCommandName("dev")} doesn't support the ${label} ${list} yet.`})}function assertNoBuildpackServices(services){let blocked=[];for(let service of services){let runtime=getBuildpackRuntime(service.builder);runtime&&blocked.push({name:service.name,runtime})}if(blocked.length>0)throw buildpackServicesDevUnsupportedError(blocked)}var httpStatusDescriptionMap=new Map([[400,"BAD_REQUEST"],[402,"PAYMENT_REQUIRED"],[403,"FORBIDDEN"],[404,"NOT_FOUND"],[405,"NOT_ALLOWED"],[410,"GONE"],[413,"PAYLOAD_TOO_LARGE"],[429,"RATE_LIMITED"],[500,"INTERNAL_SERVER_ERROR"],[501,"NOT_IMPLEMENTED"],[502,"BAD_GATEWAY"],[503,"SERVICE_UNAVAILABLE"],[504,"GATEWAY_TIMEOUT"],[508,"INFINITE_LOOP"]]),errorMessageMap=new Map([[400,"Bad request"],[402,"Payment required"],[403,"You don't have the required permissions"],[404,"The page could not be found"],[405,"Method not allowed"],[410,"The deployment has been removed"],[413,"Request Entity Too Large"],[429,"Rate limited"],[500,"A server error has occurred"],[501,"Not implemented"],[503,"The deployment is currently unavailable"],[504,"An error occurred with your deployment"],[508,"Infinite loop detected"]]),appError={title:"An error occurred with this application.",subtitle:"This is an error with the application itself, not the platform.",app_error:!0},pageNotFoundError={title:"The page could not be found.",subtitle:"The page could not be found in the application.",app_error:!0};function generateErrorMessage(statusCode,errorCode){return statusCode===404?pageNotFoundError:statusCode===502?appError:{title:errorMessageMap.get(statusCode)||"Error occurred",app_error:!1}}function generateHttpStatusDescription(statusCode){return httpStatusDescriptionMap.get(statusCode)||"UNKNOWN_ERROR"}function createErrorReporter2(recordCode){return createErrorReporter(recordCode,toDiagnostic2,telemetryCodes)}var import_escape_html=__toESM(require_escape_html(),1);function error(it){let out="<main> ";return it.error_code=="EDGE_FUNCTION_INVOCATION_FAILED"&&(out+=' <p class="error-title error-title-guilty"> <strong>This Edge Function</strong><span> has crashed.</span> </p> '),out+=" ",it.error_code=="FUNCTION_INVOCATION_FAILED"&&(out+=' <p class="error-title error-title-guilty"> <strong>This Serverless Function</strong><span> has crashed.</span> </p> '),out+=' <p class="devinfo-container"> <span class="error-code"><strong>'+it.http_status_code+"</strong>: "+(0,import_escape_html.default)(it.http_status_description)+"</span> ",it.error_code&&(out+=' <span class="devinfo-line">Code: <code>'+(0,import_escape_html.default)(it.error_code)+"</code></span> "),out+=' <span class="devinfo-line">ID: <code>'+(0,import_escape_html.default)(it.request_id)+"</code> </p> <p> <ul> <li> Check the logs in your terminal window to see the application error. </li> </ul> </p></main>",out}var import_escape_html2=__toESM(require_escape_html(),1);function error_base(it){return'<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="theme-color" content="#000"> <title>'+it.http_status_code+": "+(0,import_escape_html2.default)(it.http_status_description)+`</title> <style> html { font-size: 62.5%; box-sizing: border-box; height: -webkit-fill-available } *, ::after, ::before { box-sizing: inherit } body { font-family: "SF Pro Text", "SF Pro Icons", "Helvetica Neue", "Helvetica", "Arial", sans-serif; font-size: 1.6rem; line-height: 1.65; word-break: break-word; font-kerning: auto; font-variant: normal; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-rendering: optimizeLegibility; hyphens: auto; height: 100vh; height: -webkit-fill-available; max-height: 100vh; max-height: -webkit-fill-available; margin: 0 } ::selection { background: #79FFE1; } ::-moz-selection { background: #79FFE1; } a { cursor: pointer; color: #0070f3; text-decoration: none; transition: all .2s ease; border-bottom: 1px solid transparent } a:hover { border-bottom: 1px solid #0070f3 } ul { padding: 0; margin-left: 1.5em; list-style-type: none } li { margin-bottom: 10px } ul li:before { content: '\\02013' } li:before { display: inline-block; color: #ccc; position: absolute; margin-left: -18px; transition: color .2s ease } code { font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono, Bitstream Vera Sans Mono, Courier New, monospace, serif; font-size: .92em } code:after, code:before { content: '\`' } .container { display: flex; justify-content: center; flex-direction: column; min-height: 100% } main { max-width: 80rem; padding: 4rem 6rem; margin: auto } ul { margin-bottom: 32px } .error-title { font-size: 2rem; padding-left: 22px; line-height: 1.5; margin-bottom: 24px; } .error-title-guilty { border-left: 2px solid #ED367F; } .error-title-innocent { border-left: 2px solid #59B89C; } main p { color: #333 } .devinfo-container { border: 1px solid #ddd; border-radius: 4px; padding: 2rem; display: flex; flex-direction: column; margin-bottom: 32px } .error-code { margin: 0; font-size: 1.6rem; color: #000; margin-bottom: 1.6rem } .devinfo-line { color: #333 } .devinfo-line code, code, li { color: #000 } .devinfo-line:not(:last-child) { margin-bottom: 8px } .docs-link, .contact-link { font-weight: 500 } header, footer, footer a { display: flex; justify-content: center; align-items: center } header, footer { min-height: 100px; height: 100px; } header { border-bottom: 1px solid #eaeaea; } header h1 { font-size: 1.8rem; margin: 0; font-weight: 500; } header p { font-size: 1.3rem; margin: 0; font-weight: 500; } .header-item { display: flex; padding: 0 2rem; margin: 2rem 0; text-decoration: line-through; color: #999; } .header-item.active { color: #ff0080; text-decoration: none; } .header-item.first { border-right: 1px solid #eaeaea; } .header-item-content { display: flex; flex-direction: column; } .header-item-icon { margin-right: 1rem; margin-top: 0.6rem; } footer { border-top: 1px solid #eaeaea; } footer a { color: #000 } footer a:hover { border-bottom-color: transparent } footer svg { margin-left: .8rem } .note { padding: 8pt 16pt; border-radius: 5px; border: 1px solid #0070f3; font-size: 14px; line-height: 1.8; color: #0070f3; } @media (max-width:500px) { .devinfo-container .devinfo-line code { margin-top: .4rem } .devinfo-container .devinfo-line:not(:last-child) { margin-bottom: 1.6rem } .devinfo-container { margin-bottom: 0; } header { flex-direction: column; height: auto; min-height: auto; align-items: flex-start; } .header-item.first { border-right: none; margin-bottom: 0; } main { padding: 1rem 2rem; } body { font-size: 1.4rem; line-height: 1.55; } footer { display: none; } .note { margin-top: 16px; } } </style> </head> <body> <div class="container"> `+it.view+" </div> </body></html>"}var import_escape_html3=__toESM(require_escape_html(),1);function error_404(it){let out='<main> <p class="devinfo-container"> <span class="error-code"><strong>'+it.http_status_code+"</strong>: "+(0,import_escape_html3.default)(it.http_status_description)+"</span> ";return it.error_code&&(out+=' <span class="devinfo-line">Code: <code>'+(0,import_escape_html3.default)(it.error_code)+"</code></span> "),out+=' <span class="devinfo-line">ID: <code>'+(0,import_escape_html3.default)(it.request_id)+"</code> </p></main>",out}var import_escape_html4=__toESM(require_escape_html(),1);function error_502(it){let out='<main> <p class="devinfo-container"> <span class="error-code"><strong>'+it.http_status_code+"</strong>: "+(0,import_escape_html4.default)(it.http_status_description)+"</span> ";return it.error_code&&(out+=' <span class="devinfo-line">Code: <code>'+(0,import_escape_html4.default)(it.error_code)+"</code></span> "),out+=' <span class="devinfo-line">ID: <code>'+(0,import_escape_html4.default)(it.request_id)+"</code> </p> <p> <ul> <li> Check the logs in your terminal window to see the application error. </li> </ul> </p></main>",out}var import_escape_html5=__toESM(require_escape_html(),1);function redirect(it){return"<!doctype html><!-- https://now.sh --><h1>Redirecting ("+it.statusCode+")</h1><a>"+(0,import_escape_html5.default)(it.location)+"</a>"}var import_ms4=__toESM(require_ms(),1),import_get_port=__toESM(require_get_port(),1),import_chalk=__toESM(require_source(),1),import_frameworks2=__toESM(require_frameworks(),1);import path2 from"path";import{Transform,Writable}from"stream";function parseCronFields(expression){let parts=expression.trim().split(/\s+/);if(parts.length!==5)return null;let[minute,hour,dayOfMonth,month,dayOfWeek]=parts;return{minute,hour,dayOfMonth,month,dayOfWeek}}function expandCronField(field,min,max){let values=new Set;for(let part of field.split(",")){let stepMatch=part.match(/^(.+)\/(\d+)$/),range=stepMatch?stepMatch[1]:part,step=stepMatch?parseInt(stepMatch[2],10):1,start,end;if(range==="*")start=min,end=max;else if(range.includes("-")){let[lo,hi]=range.split("-").map(Number);start=lo,end=hi}else{let val=parseInt(range,10);start=val,end=val}for(let i=start;i<=end;i+=step)values.add(i)}return values}function nextOrWrap(sorted,current){for(let v of sorted)if(v>=current)return v;return null}function dayMatches(date,daysOfMonth,daysOfWeek,orDays){return orDays?daysOfMonth.has(date.getDate())||daysOfWeek.has(date.getDay()):daysOfMonth.has(date.getDate())&&daysOfWeek.has(date.getDay())}function getNextCronDelay(expression,now=new Date){let parsed=parseCronFields(expression);if(!parsed)return null;let minuteSet=expandCronField(parsed.minute,0,59),hourSet=expandCronField(parsed.hour,0,23),domSet=expandCronField(parsed.dayOfMonth,1,31),monthSet=expandCronField(parsed.month,1,12),dowSet=expandCronField(parsed.dayOfWeek,0,6),sortedMinutes=[...minuteSet].sort((a,b)=>a-b),sortedHours=[...hourSet].sort((a,b)=>a-b),sortedMonths=[...monthSet].sort((a,b)=>a-b),orDays=parsed.dayOfMonth!=="*"&&parsed.dayOfWeek!=="*",t=new Date(now);t.setSeconds(0,0),t.setMinutes(t.getMinutes()+1);let maxYear=t.getFullYear()+4;for(;t.getFullYear()<=maxYear;){let month=t.getMonth()+1,nextMonth=nextOrWrap(sortedMonths,month);if(nextMonth===null||nextMonth>month){let targetMonth=nextMonth??sortedMonths[0];nextMonth===null&&t.setFullYear(t.getFullYear()+1),t.setMonth(targetMonth-1,1),t.setHours(sortedHours[0],sortedMinutes[0]);continue}if(!dayMatches(t,domSet,dowSet,orDays)){t.setDate(t.getDate()+1),t.setHours(sortedHours[0],sortedMinutes[0]);continue}let hour=t.getHours(),nextHour=nextOrWrap(sortedHours,hour);if(nextHour===null||nextHour>hour){nextHour===null?(t.setDate(t.getDate()+1),t.setHours(sortedHours[0],sortedMinutes[0])):t.setHours(nextHour,sortedMinutes[0]);continue}let minute=t.getMinutes(),nextMinute=nextOrWrap(sortedMinutes,minute);if(nextMinute===null||nextMinute>minute){nextMinute===null?t.setHours(t.getHours()+1,sortedMinutes[0]):t.setMinutes(nextMinute);continue}return t.getTime()-now.getTime()}return null}var import_build_utils5=__toESM(require_build_utils(),1);var import_service_schedules=__toESM(require_service_schedules(),1);import{chmodSync,mkdirSync,readFileSync as readFileSync2,renameSync,rmSync,writeFileSync}from"node:fs";import{randomUUID}from"node:crypto";import{dirname as dirname2,isAbsolute,join as join2,normalize,sep}from"node:path";var manifest_default={nextDevWebSocketPreload:{source:"node-preloads/next-dev-websocket.cjs",destination:"node-preloads/next-dev-websocket.cjs"},devTunnelFunction:{source:"dev-tunnel/api/tunnel.ts",destination:"dev-tunnel/api/tunnel.ts"},devTunnelEnv:{source:"dev-tunnel/lib/env.ts",destination:"dev-tunnel/lib/env.ts"},devTunnelProto:{source:"dev-tunnel/lib/tunnel_pb.ts",destination:"dev-tunnel/lib/tunnel_pb.ts"}};var runtimeAssets=manifest_default;function getRuntimeAssetsDir(version=pkg_default.version,globalRoot=getGlobalPathConfig()){return join2(globalRoot,"runtime-assets",version)}function materializeRuntimeAsset(id,options={}){let definition2=runtimeAssets[id];if(!definition2)throw new Error(`Unknown runtime asset: ${String(id)}`);let source=validateRelativePath(id,"source",definition2.source),destination=validateRelativePath(id,"destination",definition2.destination),data=readRuntimeAsset(source),destinationPath=join2(getRuntimeAssetsDir(options.version??pkg_default.version,options.globalRoot??getGlobalPathConfig()),destination),destinationDir=dirname2(destinationPath),temporaryPath=`${destinationPath}.${process.pid}.${randomUUID()}.tmp`;mkdirSync(destinationDir,{recursive:!0});try{writeFileSync(temporaryPath,new Uint8Array(data.buffer,data.byteOffset,data.byteLength)),definition2.executable&&chmodSync(temporaryPath,493);try{renameSync(temporaryPath,destinationPath)}catch(error2){let code=error2.code;if(code!=="EEXIST"&&code!=="EPERM")throw error2;rmSync(destinationPath,{force:!0}),renameSync(temporaryPath,destinationPath)}}finally{rmSync(temporaryPath,{force:!0})}return destinationPath}function readRuntimeAsset(source,moduleDir=__dirname){let candidates=[join2(moduleDir,"runtime-assets",source),join2(moduleDir,"..","runtime-assets",source),join2(moduleDir,"..","..","runtime-assets",source)],lastError;for(let candidate of candidates)try{return readFileSync2(candidate)}catch(error2){if(error2.code!=="ENOENT")throw error2;lastError=error2}throw lastError}function validateRelativePath(id,field,value){let normalized=normalize(value);if(!value||isAbsolute(value)||normalized===".."||normalized.startsWith(`..${sep}`))throw new Error(`Runtime asset "${id}" has an invalid ${field} path: ${JSON.stringify(value)}`);return normalized}function injectNextDevWebSocketShimIfNeeded(env,command,projectSettings,runtimeOptions){if(!shouldInjectNextDevWebSocketShim(command,projectSettings))return;let shimPath=materializeRuntimeAsset("nextDevWebSocketPreload",runtimeOptions);return env.NODE_OPTIONS=prependNodeRequireOption(env.NODE_OPTIONS,shimPath),shimPath}function shouldInjectNextDevWebSocketShim(command,projectSettings){return projectSettings?.framework==="nextjs"||/(?:^|\s)(?:next|next\.js)(?:\s+dev)?(?:\s+-|\s*$|$)/.test(command)}function prependNodeRequireOption(nodeOptions,requirePath){let requireOption=`--require ${JSON.stringify(requirePath)}`;return nodeOptions?`${requireOption} ${nodeOptions}`:requireOption}function replaceDevCommandPort(command,port){return command.replace(/\$PORT/g,`${port}`).replace(/%PORT%/g,`${port}`)}var import_ms3=__toESM(require_ms(),1);var DEV_RUNTIME_CACHE_PREFIX="/_svc/_cache/",DEV_RUNTIME_CACHE_API_PREFIX="/v1/suspense-cache/",DEV_RUNTIME_CACHE_ITEM_PREFIX=`${DEV_RUNTIME_CACHE_PREFIX}v1/suspense-cache/`,HEADER_CACHE_STATE="x-vercel-cache-state",HEADER_CACHE_TAGS="x-vercel-cache-tags",HEADER_REVALIDATE="x-vercel-revalidate",HEADER_CACHE_ITEM_NAME="x-vercel-cache-item-name",TICK_INTERVAL=(0,import_ms3.default)("1m");function getDevRuntimeCacheEnv(origin,itemPrefix=DEV_RUNTIME_CACHE_ITEM_PREFIX){return{RUNTIME_CACHE_ENDPOINT:`${origin}${itemPrefix}`,RUNTIME_CACHE_HEADERS:JSON.stringify({authorization:`Bearer ${DEV_RESOURCE_TOKEN}`})}}var RuntimeCacheStore=class{constructor(){this.entries=new Map;this.tagExpirations=new Map;this.sequence=0;this.tickTimer=setInterval(()=>this.tick(),TICK_INTERVAL),this.tickTimer.unref()}get(key){let entry=this.entries.get(key);return entry?this.isStale(entry)?(this.entries.delete(key),null):{value:entry.value,tags:entry.tags,ageSeconds:Math.floor((Date.now()-entry.lastModified)/1e3)}:null}set(key,value,options={}){let ttlSeconds=options.ttlSeconds;this.entries.set(key,{value,tags:options.tags??[],ttlMs:ttlSeconds&&ttlSeconds>0?ttlSeconds*1e3:null,lastModified:Date.now(),sequence:++this.sequence})}delete(key){this.entries.delete(key)}expireTags(tags){let sequence=++this.sequence;for(let tag of tags)this.tagExpirations.set(tag,sequence)}size(){return this.entries.size}stop(){clearInterval(this.tickTimer)}isStale(entry){if(entry.ttlMs!==null&&entry.lastModified+entry.ttlMs<=Date.now())return!0;for(let tag of entry.tags){let expiredAt=this.tagExpirations.get(tag);if(expiredAt!==void 0&&expiredAt>entry.sequence)return!0}return!1}tick(){for(let[key,entry]of this.entries)this.isStale(entry)&&this.entries.delete(key)}};var STARTUP_TIMEOUT=(0,import_ms4.default)("5m"),SERVICE_COLORS=[import_chalk.default.cyan,import_chalk.default.magenta,import_chalk.default.yellow,import_chalk.default.green,import_chalk.default.blue];function createServiceLogger(serviceName,colorIndex,maxNameLength){let color=SERVICE_COLORS[colorIndex%SERVICE_COLORS.length],padding=" ".repeat(maxNameLength-serviceName.length),prefix=color(`[${serviceName}]`)+padding,createTransform=streamLabel=>{let buffer="",labelPrefix=output_manager_default.debugEnabled?`${prefix} ${import_chalk.default.gray(`(${streamLabel})`)}`:prefix;return new Transform({transform(chunk,_encoding,callback){buffer+=chunk.toString();let lines=buffer.split(`
|
|
24
24
|
`);if(buffer=lines.pop()||"",lines.length>0){let prefixed=lines.map(line=>`${labelPrefix} ${line}`).join(`
|
|
25
25
|
`);callback(null,prefixed+`
|
|
26
26
|
`)}else callback(null,"")},flush(callback){buffer?callback(null,`${labelPrefix} ${buffer}
|
|
@@ -39,7 +39,7 @@ ${partHeaders}\r
|
|
|
39
39
|
`)))}parts.push(Uint8Array.from(Buffer.from(`--${boundary}--\r
|
|
40
40
|
`)));let body=Buffer.concat(parts);res.writeHead(200,{"Content-Type":`multipart/mixed; boundary=${boundary}`,"Content-Length":body.length}),res.end(body);return}let leaseMatch=topicPath.match(/^([A-Za-z0-9_-]+)\/consumer\/([A-Za-z0-9_-]+)\/lease\/([^/]+)(?:\/visibility)?$/);if(leaseMatch&&(req.method==="DELETE"||req.method==="PATCH")){let[,,consumer,receiptHandle]=leaseMatch,messageId=this.queueBroker.findMessageIdByReceiptHandle(consumer,receiptHandle);if(!messageId){res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Message not found"}));return}if(req.method==="DELETE"){this.queueBroker.acknowledge(messageId,consumer,receiptHandle),res.writeHead(204),res.end();return}let body=await(0,import_raw_body2.default)(req),timeoutSeconds=DEV_QUEUES_DEFAULT_VISIBILITY_TIMEOUT_SECONDS;try{let parsed=JSON.parse(body.toString());typeof parsed.visibilityTimeoutSeconds=="number"&&parsed.visibilityTimeoutSeconds>=0&&(timeoutSeconds=parsed.visibilityTimeoutSeconds)}catch(err){output_manager_default.debug(`queues: failed to parse visibility timeout body: ${err}`)}this.queueBroker.changeVisibility(messageId,consumer,receiptHandle,timeoutSeconds),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}res.writeHead(404),res.end("Not Found")};this.handleRuntimeCacheRoute=async(req,res,pathname)=>{let store=this.runtimeCache;if(!store){res.writeHead(503),res.end("Runtime Cache not initialized");return}if(!pathname.startsWith(DEV_RUNTIME_CACHE_API_PREFIX)){res.writeHead(404),res.end("Not Found");return}let itemPath=pathname.slice(DEV_RUNTIME_CACHE_API_PREFIX.length),searchParams=new URL2(req.url||"/","http://localhost").searchParams;if(itemPath==="revalidate"){if(req.method!=="POST"){res.writeHead(405),res.end("Method Not Allowed");return}let tags=(searchParams.get("tags")||"").split(",").map(tag=>tag.trim()).filter(Boolean),itemId=searchParams.get("itemId")||void 0;if(tags.length===0&&!itemId){res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"No tags or itemId provided"}));return}tags.length>0&&(store.expireTags(tags),output_manager_default.debug(`runtime cache: expired tags "${tags.join(",")}"`)),itemId&&(store.delete(itemId),output_manager_default.debug(`runtime cache: expired item "${itemId}"`)),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({revalidated:!0}));return}let key;try{key=decodeURIComponent(itemPath)}catch{res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid cache key"}));return}if(!key){res.writeHead(404),res.end("Not Found");return}if(req.method==="GET"){let hit=store.get(key);if(!hit){output_manager_default.debug(`runtime cache: MISS "${key}"`),res.writeHead(404),res.end("Not Found");return}output_manager_default.debug(`runtime cache: HIT "${key}"`);let headers={"Content-Type":"application/json","Content-Length":hit.value.length,[HEADER_CACHE_STATE]:"fresh",Age:String(hit.ageSeconds)};hit.tags.length>0&&(headers[HEADER_CACHE_TAGS]=hit.tags.join(",")),res.writeHead(200,headers),res.end(hit.value);return}if(req.method==="POST"){let revalidateHeader=req.headers[HEADER_REVALIDATE],ttlSeconds;if(revalidateHeader)if(revalidateHeader==="Infinity"||["false","False","FALSE","f","F"].includes(revalidateHeader))ttlSeconds=DEV_RUNTIME_CACHE_ONE_YEAR_SECONDS;else if(/^[+-]?\d+$/.test(revalidateHeader)){let parsedRevalidate=Number(revalidateHeader);if(!Number.isSafeInteger(parsedRevalidate)||parsedRevalidate<0){res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid revalidate value"}));return}if(parsedRevalidate===0){res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}ttlSeconds=parsedRevalidate}else{res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid revalidate value"}));return}let value;try{value=await(0,import_raw_body2.default)(req,{limit:DEV_RUNTIME_CACHE_MAX_ITEM_SIZE})}catch(err){if(err.statusCode===413){res.writeHead(413,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Cache item is too large"}));return}throw err}let tagsHeader=req.headers[HEADER_CACHE_TAGS];store.set(key,value,{ttlSeconds,tags:(tagsHeader||"").split(",").map(tag=>tag.trim()).filter(Boolean)});let name=req.headers[HEADER_CACHE_ITEM_NAME];output_manager_default.debug(`runtime cache: SET "${key}"${name?` (${name})`:""} ${value.length} bytes`),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}if(req.method==="DELETE"){store.delete(key),output_manager_default.debug(`runtime cache: DELETE "${key}"`),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}res.writeHead(405),res.end("Method Not Allowed")};this.serveProjectAsNowV2=async(req,res,requestId,vercelConfig,routes=vercelConfig.routes,callLevel=0)=>{let{debug}=output_manager_default;if(callLevel===0&&await this.handleSchedulesProxyRequest(req,res))return;let parsed=url3.parse(req.url||"/");if(typeof parsed.pathname=="string"&&parsed.pathname.includes("//")){let location=parsed.pathname.replace(/\/+/g,"/");if(parsed.search&&(location+=parsed.search),req.method==="GET"){await this.sendRedirect(req,res,requestId,location,301);return}debug(`Rewriting URL from "${req.url}" to "${location}"`),req.url=location}let queueProxyPrefix=`${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`,runtimeCacheProxyPrefix=`${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}`;if(callLevel===0&&this.queueBroker){let pathname=parsed.pathname||"/";if(pathname.startsWith(`${queueProxyPrefix}/`)){if(!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}await this.handleQueuesRoute(req,res,pathname.slice(queueProxyPrefix.length));return}}if(callLevel===0){let pathname=parsed.pathname||"/";if(pathname.startsWith(`${runtimeCacheProxyPrefix}/`)){if(!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}await this.handleRuntimeCacheRoute(req,res,pathname.slice(runtimeCacheProxyPrefix.length));return}}if(callLevel===0&&this.bulkRedirects){let bulkMatch=resolveBulkRedirect(this.bulkRedirects,req.url||"/",typeof req.headers.host=="string"?req.headers.host:void 0);if(bulkMatch){debug(`Bulk redirect ${bulkMatch.statusCode}: ${req.url} -> ${bulkMatch.location}`),await this.sendRedirect(req,res,requestId,bulkMatch.location,bulkMatch.statusCode);return}}if(callLevel===0&&this.orchestrator){let pathname=parsed.pathname||"/",service=this.orchestrator.getServiceForRoute(pathname);if(service){debug(`Found service: ${service.name}`);let upstream=`http://${service.host}:${service.port}`;debug(`Proxying to service "${service.name}": ${upstream}`);let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.setResponseHeaders(res,requestId),proxyPass(req,res,upstream,this,requestId,!1)}}callLevel===0&&await this.updateBuildMatches(vercelConfig),this.blockingBuildsPromise&&(debug("Waiting for builds to complete before handling request"),await this.blockingBuildsPromise);let getReqUrl=rr=>{if(rr.dest){if(rr.query){let destParsed=url3.parse(rr.dest),destQuery=parseQueryString(destParsed.search);return Object.assign(destQuery,rr.query),destParsed.search=formatQueryString(destQuery),url3.format(destParsed)}return rr.dest}return req.url},handleMap=getRoutesTypes(routes),missRoutes=handleMap.get("miss")||[],hitRoutes=handleMap.get("hit")||[],errorRoutes=handleMap.get("error")||[],filesystemRoutes=handleMap.get("filesystem")||[],phases=[null,"filesystem"],routeResult=null,match=null,statusCode,prevUrl=req.url,prevHeaders={},requestTransforms=[],responseTransforms,middlewares=[...this.buildMatches.values()].filter(m=>m.config?.middleware===!0);for(let middleware of middlewares){let startMiddlewareResult,middlewarePid,{envConfigs,files,devCacheDir,cwd:workPath}=this;try{let{builder:builder2}=middleware.builderWithPkg;if(typeof builder2.startDevServer=="function"&&(startMiddlewareResult=await builder2.startDevServer({files,entrypoint:middleware.entrypoint,workPath,repoRootPath:this.repoRoot,config:{projectSettings:this.projectSettings,...middleware.config},meta:{isDev:!0,...this.getDevResourceMeta(),devCacheDir,requestUrl:req.url,env:this.getBuilderDevEnv(middleware,envConfigs.runEnv),buildEnv:{...envConfigs.buildEnv}}})),startMiddlewareResult){let{port,pid,shutdown}=startMiddlewareResult;middlewarePid=pid,this.shutdownCallbacks.set(pid,shutdown),debug(`Invoking middleware "${middleware.src}" (port=${port})`);let middlewareReqHeaders=nodeHeadersToFetchHeaders(req.headers),proxyHeaders=this.getProxyHeaders(req,requestId,!0);for(let[name,value]of nodeHeadersToFetchHeaders(proxyHeaders))middlewareReqHeaders.set(name,value);let middlewareReqPath=url3.parse(req.url||"/").path||"/",middlewareRes=await directFetch(`http://127.0.0.1:${port}${middlewareReqPath}`,{headers:middlewareReqHeaders,method:req.method,redirect:"manual"}),middlewareBody=Buffer.from(await middlewareRes.arrayBuffer());if(middlewareRes.status===500&&middlewareBody.byteLength===0){await this.sendError(req,res,requestId,"EDGE_FUNCTION_INVOCATION_FAILED",500);return}res.statusCode=middlewareRes.status;let rewritePath="",contentType2="",shouldContinue=!1,skipMiddlewareHeaders=new Set(["date","connection","content-length","transfer-encoding"]),middlewareHeaders=applyOverriddenHeaders(req.headers,middlewareRes.headers);for(let[name,value]of middlewareHeaders)name==="x-middleware-next"?shouldContinue=value==="1":name==="x-middleware-rewrite"?(rewritePath=value,shouldContinue=!0):name==="content-type"?contentType2=value:skipMiddlewareHeaders.has(name)||(applyChainResponseHeader(res,name,value),req.headers[name]=value);if(!shouldContinue){this.setResponseHeaders(res,requestId),middlewareBody.length>0?(res.setHeader("content-length",middlewareBody.length),contentType2&&res.setHeader("content-type",contentType2),res.end(middlewareBody)):res.end();return}if(rewritePath){debug(`Detected rewrite path from middleware: "${rewritePath}"`),prevUrl=rewritePath;let beforeRewriteUrl=req.url||"/";if(isURL(rewritePath)){let rewriteUrlParsed=new URL2(rewritePath);if(this.address.origin===rewriteUrlParsed.origin)req.url=rewritePath.slice(rewriteUrlParsed.origin.length)||"/",prevUrl=req.url;else{debug(`ProxyPass: ${rewritePath}`),this.setResponseHeaders(res,requestId),proxyPass(req,res,rewritePath,this,requestId);return}}else{let rewriteUrlParsed=url3.parse(beforeRewriteUrl);rewriteUrlParsed.search=url3.parse(rewritePath).search,req.url=url3.format(rewriteUrlParsed)}debug(`Rewrote incoming HTTP URL from "${beforeRewriteUrl}" to "${req.url}"`)}}}catch(err){(0,import_error_utils.isSpawnError)(err)&&err.code==="ENOENT"&&(err.message=`Command not found: ${import_chalk2.default.cyan(err.path,...err.spawnargs)}
|
|
41
41
|
Please ensure that ${cmd(err.path)} is properly installed`,err.link="https://vercel.link/command-not-found"),output_manager_default.prettyError(err),await this.sendError(req,res,requestId,"MIDDLEWARE_INVOCATION_FAILED",500);return}finally{middlewarePid&&this.killBuilderDevServer(middlewarePid)}}for(let phase of phases){statusCode=void 0;let phaseRoutes=handleMap.get(phase)||[];if(routeResult=await devRouter(prevUrl,req.method,phaseRoutes,this,vercelConfig,prevHeaders,missRoutes,phase),routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms),routeResult.continue&&(routeResult.dest&&(prevUrl=getReqUrl(routeResult)),routeResult.headers&&(prevHeaders=routeResult.headers)),callLevel===0&&this.orchestrator&&!routeResult.continue&&isServiceDestination(routeResult.matched_route))return this.delegateToService(req,res,requestId,routeResult.matched_route,vercelConfig,requestTransforms,responseTransforms);if(routeResult.isDestUrl){let destParsed=url3.parse(routeResult.dest),destQuery=parseQueryString(destParsed.search);Object.assign(destQuery,routeResult.query),destParsed.search=formatQueryString(destQuery);let destUrl=url3.format(destParsed);return this.prepareTransforms(req,requestTransforms,responseTransforms),debug(`ProxyPass: ${destUrl}`),this.setResponseHeaders(res,requestId),proxyPass(req,res,destUrl,this,requestId)}if(match=await findBuildMatch(this.buildMatches,this.files,routeResult.dest,this,vercelConfig),await this.exitWithStatus(match,routeResult,phase,req,res,requestId,responseTransforms))return;if(!match&&missRoutes.length>0){if(routeResult=await devRouter(getReqUrl(routeResult),req.method,missRoutes,this,vercelConfig,routeResult.headers,[],"miss"),routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms),match=await findBuildMatch(this.buildMatches,this.files,routeResult.dest,this,vercelConfig),await this.exitWithStatus(match,routeResult,phase,req,res,requestId,responseTransforms))return}else if(match&&hitRoutes.length>0){let prevStatus=routeResult.status;routeResult=await devRouter(getReqUrl(routeResult),req.method,hitRoutes,this,vercelConfig,routeResult.headers,[],"hit"),routeResult.status=prevStatus,routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms)}if(statusCode=routeResult.status,match||phase===null&&filesystemRoutes.length===0)break}if(!match&&routeResult&&errorRoutes.length>0){let routeResultForError=await devRouter(getReqUrl(routeResult),req.method,errorRoutes,this,vercelConfig,routeResult.headers,[],"error"),{matched_route}=routeResultForError,matchForError=await findBuildMatch(this.buildMatches,this.files,routeResultForError.dest,this,vercelConfig);if(matchForError)debug("Route match detected in error phase, breaking loop"),routeResult=routeResultForError,statusCode=routeResultForError.status,match=matchForError,routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms);else if(matched_route&&matched_route.src&&!matched_route.dest&&(debug("Route without `dest` detected in error phase, attempting to exit early"),await this.exitWithStatus(matchForError,routeResultForError,"error",req,res,requestId,responseTransforms)))return}if(!routeResult)throw dev.DEV_INTERNAL_NO_ROUTE_RESULT();let{dest,query,headers}=routeResult;for(let[name,value]of Object.entries(headers))res.setHeader(name,value);statusCode&&Object.defineProperty(res,"statusCode",{get(){return statusCode},set(_){}});let requestPath=dest.replace(/^\//,"");if(!match){if(this.devProcessOrigin){let upstream=this.devProcessOrigin;debug(`Proxying to frontend dev server: ${upstream}`);let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;this.setResponseHeaders(res,requestId);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);return origUrl.pathname=dest,Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format(origUrl),this.prepareTransforms(req,requestTransforms,responseTransforms),proxyPass(req,res,upstream,this,requestId,!1)}(statusCode===404&&routeResult.phase==="miss"||!this.renderDirectoryListing(req,res,requestPath,requestId))&&await this.send404(req,res,requestId);return}let buildRequestPath=match.buildResults.has(null)?null:requestPath,buildResult=match.buildResults.get(buildRequestPath);if(buildResult&&Array.isArray(buildResult.routes)&&buildResult.routes.length>0){let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);origUrl.pathname=dest,Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery);let newUrl=url3.format(origUrl);debug(`Checking build result's ${buildResult.routes.length} \`routes\` to match ${newUrl}`);let matchedRoute=await devRouter(newUrl,req.method,buildResult.routes,this,vercelConfig);if(matchedRoute.found&&callLevel===0){debug(`Found matching route ${matchedRoute.dest} for ${newUrl}`),req.url=newUrl,await this.serveProjectAsNowV2(req,res,requestId,vercelConfig,buildResult.routes,callLevel+1);return}}let{builder,pkg:builderPkg}=match.builderWithPkg;if(typeof builder.startDevServer=="function"){let devServerResult=null;try{devServerResult=await this.startBuildMatchDevServer(match,requestPath)}catch(err){(0,import_error_utils.isSpawnError)(err)&&err.code==="ENOENT"&&(err.message=`Command not found: ${import_chalk2.default.cyan(err.path,...err.spawnargs)}
|
|
42
|
-
Please ensure that ${cmd(err.path)} is properly installed`,err.link="https://vercel.link/command-not-found"),output_manager_default.prettyError(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}if(devServerResult){requestId=generateRequestId(this.podId,!0);let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown),persistent||res.once("close",()=>{this.killBuilderDevServer(pid)}),debug(`Proxying to "${builderPkg.name}" dev server (port=${port}, pid=${pid})`);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search});let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,`http://127.0.0.1:${port}`,this,requestId,!1)}else debug(`Skipping \`startDevServer()\` for ${match.entrypoint}`)}let foundAsset=findAsset(match,requestPath,vercelConfig);if(!foundAsset&&callLevel===0&&(await this.triggerBuild(match,buildRequestPath,req,vercelConfig),foundAsset=findAsset(match,requestPath,vercelConfig)),this.devProcessOrigin&&(!foundAsset||foundAsset&&foundAsset.asset.type!=="Lambda")){debug("Proxying to frontend dev server");let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,this.devProcessOrigin,this,requestId,!1)}if(!foundAsset){await this.send404(req,res,requestId);return}let{asset,assetKey}=foundAsset;switch(debug(`Serving asset: [${asset.type}] ${assetKey} ${asset.contentType||""}`),asset.type){case"FileFsRef":this.setResponseHeaders(res,requestId);let staticResHeaders={};applyResponseTransforms(staticResHeaders,responseTransforms??[]);for(let[name,value]of Object.entries(staticResHeaders))value!==void 0&&res.setHeader(name,value);return req.url=`/${basename(asset.fsPath)}`,serveStaticFile(req,res,dirname3(asset.fsPath),{headers:[{source:"**/*",headers:[{key:"Content-Type",value:asset.contentType||getMimeType(assetKey)}]}]});case"FileBlob":let headers2={"Content-Length":asset.data.length,"Content-Type":asset.contentType||getMimeType(assetKey)};applyResponseTransforms(headers2,responseTransforms??[]),this.setResponseHeaders(res,requestId,headers2),res.end(asset.data);return;case"Lambda":if(!asset.fn){await this.sendError(req,res,requestId,"INTERNAL_LAMBDA_NOT_FOUND");return}requestId=generateRequestId(this.podId,!0);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search}),applyRequestTransforms(req,requestTransforms);let path6=req.url||"/",body=await(0,import_raw_body2.default)(req);debug(`Invoking lambda: "${assetKey}" with ${path6}`);let result;try{result=await this.invokeBuiltLambda(asset,req,requestId,body)}catch(err){console.error(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}statusCode||(res.statusCode=result.statusCode);let lambdaHeaders=result.headers??{};applyResponseTransforms(lambdaHeaders,responseTransforms??[]),this.setResponseHeaders(res,requestId,lambdaHeaders);let resBody;return result.encoding==="base64"&&typeof result.body=="string"?resBody=Buffer.from(result.body,"base64"):resBody=result.body,res.end(resBody);default:await this.sendError(req,res,requestId,"UNKNOWN_ASSET_TYPE")}};if(this.cwd=cwd,this.repoRoot=options.repoRoot??cwd,this.envConfigs={buildEnv:{},runEnv:{},allEnv:{}},this.envValues=options.envValues||{},this.projectId=options.projectId,this.orgId=options.orgId,this.queuePort=options.queuePort,this.runtimeCachePort=options.runtimeCachePort,this.schedulesPort=options.schedulesPort,this.routing=options.routing??!0,this.devCommandPort=options.devCommandPort,!this.routing&&!this.devCommandPort)throw new Error("Running without the router needs a `devCommandPort`");this.scheduleBroker=new import_local_schedules2.ScheduleBroker({ownerId:this.orgId??"team_local",projectId:this.projectId??"prj_local",trackId:"development",dispatch:invocation=>this.dispatchSchedule(invocation),onError:(err,invocation)=>{try{output_manager_default.error(`Failed to dispatch schedule "${invocation.schedule.name}": ${(0,import_error_utils.errorToString)(err)}`)}catch{}}}),this.resourceProxyToken=randomBytes2(32).toString("base64url"),this.reportError=createErrorReporter2(code=>options.onErrorCode?.(code)),this.files={},this.originalProjectSettings=options.projectSettings,this.projectSettings=options.projectSettings,this.services=options.services,this.useImplicitServicesEnvInjection=options.useImplicitServicesEnvInjection??!0,this.caseSensitive=!1,this.apiDir=null,this.apiExtensions=new Set,this.proxy=import_http_proxy_node16.default.createProxyServer({changeOrigin:!0,ws:!0,xfwd:!0}),this.proxy.on("proxyRes",(proxyRes,req)=>{proxyRes.headers.server="Vercel";let responseTransforms=this.responseTransformsByReq.get(req);responseTransforms&&(this.responseTransformsByReq.delete(req),applyResponseTransforms(proxyRes.headers,responseTransforms))}),this.proxy.on("error",(err,req,res)=>{if(output_manager_default.debug(`Proxy error for ${req?.url??"unknown request"}: ${(0,import_error_utils.errorToString)(err)}`),!!res){if("destroy"in res&&typeof res.destroy=="function"){res.destroy();return}res instanceof http.ServerResponse&&(res.headersSent||res.writeHead(502),res.end())}}),this.server=http.createServer(this.devServerHandler),this.server.timeout=0,this.queueServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.queueOrigin,this.handleQueuesRoute)}),this.runtimeCacheServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.runtimeCacheOrigin,this.handleRuntimeCacheRoute)}),this.schedulesServer=http.createServer((req,res)=>{this.schedulesSession&&res.setHeader(LOCAL_SCHEDULES_SESSION_HEADER,this.schedulesSession.session.id),this.handleResourceServerRequest(req,res,this.schedulesOrigin,this.handleSchedulesRoute)}),this.stopping=!1,this.buildMatches=new Map,this.inProgressBuilds=new Map,this.devCacheDir=join4(getVercelDirectory(cwd),"cache"),this.vercelConfigWarning=!1,this.getVercelConfigPromise=null,this.blockingBuildsPromise=null,this.startPromise=null,this.bulkRedirects=null,this.bulkRedirectsSignature=null,this.bulkRedirectsLastPath=null,this.bulkRedirectsResolvedPath=null,this.bulkRedirectsDirty=!0,this.watchAggregationId=null,this.watchAggregationEvents=[],this.watchAggregationTimeout=500,this.filter=path6=>!!path6,this.podId=Math.random().toString(32).slice(-5),this.shutdownCallbacks=new Map}get address(){if(!this._address)throw dev.DEV_INTERNAL_ADDRESS_UNAVAILABLE();return this._address}shouldUseServicesOrchestrator(){return!!(this.services&&this.services.length>0)}hasSubscribers(){return!!this.sidecars?.length}getDevQueueEnv(){return this.queueOrigin?getDevQueueEnv(this.queueOrigin,this.hasSubscribers()):{}}getDevRuntimeCacheEnv(env){return!this.runtimeCacheOrigin||env.RUNTIME_CACHE_ENDPOINT?{}:process.env.RUNTIME_CACHE_ENDPOINT?{RUNTIME_CACHE_ENDPOINT:process.env.RUNTIME_CACHE_ENDPOINT,...process.env.RUNTIME_CACHE_HEADERS?{RUNTIME_CACHE_HEADERS:process.env.RUNTIME_CACHE_HEADERS}:{}}:getDevRuntimeCacheEnv(this.runtimeCacheOrigin,DEV_RUNTIME_CACHE_API_PREFIX)}get resourceEndpoints(){if(!this.queueOrigin||!this.runtimeCacheOrigin)throw new Error("Local resource servers have not started");let proxied=(direct,path6)=>this.routing?`${this.address.origin}${path6}`:direct,runtimeCache=`${this.runtimeCacheOrigin}${DEV_RUNTIME_CACHE_API_PREFIX}`;return{queues:{direct:this.queueOrigin,proxy:proxied(this.queueOrigin,`${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`)},runtimeCache:{direct:runtimeCache,proxy:proxied(runtimeCache,`${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}${DEV_RUNTIME_CACHE_API_PREFIX}`)},...this.schedulesOrigin?{schedules:{direct:this.schedulesOrigin,proxy:proxied(this.schedulesOrigin,`${DEV_SCHEDULES_PROXY_PREFIX}/${this.resourceProxyToken}`)}}:{}}}getDevResourceMeta(){return{devResourceEndpoints:this.resourceEndpoints}}handleResourceServerRequest(req,res,origin,handler){if(!origin||!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}if(!isValidDevResourceHost(origin,req.headers.host)){res.writeHead(403),res.end("Forbidden");return}let pathname=new URL2(req.url||"/","http://127.0.0.1").pathname;handler(req,res,pathname).catch(err=>{output_manager_default.debug(`Local resource request failed for ${req.url||"/"}: ${(0,import_error_utils.errorToString)(err)}`),res.headersSent||res.writeHead(500),res.end("Internal Server Error")})}isAuthorizedResourceRequest(req,token){let authorization=req.headers.authorization;if(typeof authorization!="string")return!1;let encoder=new TextEncoder,actual=encoder.encode(authorization),expected=encoder.encode(`Bearer ${token}`);return actual.length===expected.length&&timingSafeEqual(actual,expected)}getBuilderDevEnv(match,env){let result={...env,...getDevSchedulesEnv(this.schedulesOrigin)};if(match.builderWithPkg.pkg.name!=="@vercel/container")return result;let endpoints=this.resourceEndpoints;return Object.assign(result,getDevSchedulesEnv(endpoints.schedules?.proxy,!0)),result.VERCEL_QUEUE_BASE_URL===endpoints.queues.direct&&Object.assign(result,getDevQueueEnv(endpoints.queues.proxy,result.VERCEL_HAS_WORKER_SERVICES!==void 0)),result.RUNTIME_CACHE_ENDPOINT===endpoints.runtimeCache.direct&&Object.assign(result,getDevRuntimeCacheEnv(endpoints.runtimeCache.proxy,"")),result}getSidecarDevMeta(match){let serviceCount=(this.sidecars??[]).filter(sidecar=>sidecar.builder.use!==match.use?!1:!sidecar.workspace||sidecar.workspace===".").length;return serviceCount>0?{serviceCount}:{}}async setupBuilderDevSidecars(){if(this.shouldUseServicesOrchestrator())return;let sidecars=this.sidecars??[];if(sidecars.length===0)return;Object.assign(this.envConfigs.runEnv,this.getDevQueueEnv());let services=sidecars.map(toOrchestratorService),orchestrator=new ServicesOrchestrator({services,cwd:this.cwd,repoRoot:this.repoRoot,env:this.envConfigs.allEnv,proxyOrigin:this.address.origin,resourceEndpoints:this.resourceEndpoints,useImplicitEnvInjection:!1,preferServiceBuilder:!0,onQueueSubscriptions:(serviceName,subscriptions)=>this.queueBroker?.updateServiceSubscriptions(serviceName,subscriptions)});this.sidecarOrchestrator=orchestrator,this.queueBroker?.registerServices(services);try{await orchestrator.startAll()}catch(err){throw await orchestrator.stopAll(),this.sidecarOrchestrator=void 0,this.sidecars=[],err}output_manager_default.log(`Started ${sidecars.length} development ${(0,import_pluralize2.default)("sidecar",sidecars.length)}`)}async exit(code=1){await this.stop(code),process.exit(code)}enqueueFsEvent(type,path6){this.bulkRedirectsResolvedPath&&(path6===this.bulkRedirectsResolvedPath||path6.startsWith(this.bulkRedirectsResolvedPath+sep2))&&(this.bulkRedirectsDirty=!0),this.watchAggregationEvents.push({type,path:path6}),this.watchAggregationId===null&&(this.watchAggregationId=setTimeout(()=>{let events=this.watchAggregationEvents.slice();this.watchAggregationEvents.length=0,this.watchAggregationId=null,this.handleFilesystemEvents(events).catch(err=>{output_manager_default.prettyError(err),(0,import_error_utils.isError)(err)&&typeof err.stack=="string"&&output_manager_default.debug(err.stack)})},this.watchAggregationTimeout))}async handleFilesystemEvents(events){if(this.stopping)return;output_manager_default.debug(`Filesystem watcher notified of ${events.length} events`);let filesChanged=new Set,filesRemoved=new Set,distPaths=[];for(let buildMatch of this.buildMatches.values())for(let buildResult of buildMatch.buildResults.values())buildResult.distPath&&distPaths.push(buildResult.distPath);if(events=events.filter(event=>distPaths.every(distPath=>!event.path.startsWith(distPath))),events.length!==0){this.functionReconciliations++;try{this.configGeneration++,this.functionDiscovery=void 0;for(let event of events)event.type==="add"?await this.handleFileCreated(event.path,filesChanged,filesRemoved):event.type==="unlink"?this.handleFileDeleted(event.path,filesChanged,filesRemoved):event.type==="change"&&await this.handleFileModified(event.path,filesChanged,filesRemoved);let vercelConfig=await this.getVercelConfig();if(this.stopping)return;await this.updateBuildMatches(vercelConfig);let filesChangedArray=[...filesChanged],filesRemovedArray=[...filesRemoved],needsRebuild=new Map;for(let match of this.buildMatches.values()){this.canonicalizeFunctionBuild(match);for(let[requestPath,result]of match.buildResults)if(!needsRebuild.has(result)&&Array.isArray(result.watch)){for(let pattern of result.watch)if(minimatches(filesChangedArray,pattern)||minimatches(filesRemovedArray,pattern)){needsRebuild.set(result,[requestPath,match]);break}}}if(needsRebuild.size>0){output_manager_default.debug(`Triggering ${needsRebuild.size} rebuilds`),filesChangedArray.length>0&&output_manager_default.debug(`Files changed: ${filesChangedArray.join(", ")}`),filesRemovedArray.length>0&&output_manager_default.debug(`Files removed: ${filesRemovedArray.join(", ")}`);for(let[result,[requestPath,match]]of needsRebuild)requestPath===null||await shouldServe(match,this.files,requestPath,this,vercelConfig)?this.triggerBuild(match,requestPath,null,vercelConfig,result,filesChangedArray,filesRemovedArray).catch(err=>{output_manager_default.warn(`An error occurred while rebuilding \`${match.src}\`:`),console.error(err.stack)}):output_manager_default.debug(`Not rebuilding because \`shouldServe()\` returned \`false\` for "${match.use}" request path "${requestPath}"`)}}finally{this.functionReconciliations--}}}async handleFileCreated(fsPath,changed,removed){let name=relative(this.cwd,fsPath);try{await this.getVercelConfig(),this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath});let extensionless=this.getExtensionlessFile(name);extensionless&&(this.files[extensionless]=await import_build_utils9.FileFsRef.fromFsPath({fsPath})),fileChanged(name,changed,removed),output_manager_default.debug(`File created: ${name}`)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File created, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}handleFileDeleted(fsPath,changed,removed){let name=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_utils9.FileFsRef.fromFsPath({fsPath}),fileChanged(name,changed,removed),output_manager_default.debug(`File modified: ${name}`)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File modified, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}async updateBuildMatches(vercelConfig,isInitial=!1){let fileList=this.resolveBuildFiles(this.files),matches=await getBuildMatches(vercelConfig,this.cwd,this,fileList),sources=matches.map(m=>m.src);isInitial&&fileList.length===0&&output_manager_default.warn("There are no files inside your deployment.");let ops=[];for(let src of this.buildMatches.keys())if(!sources.includes(src)){output_manager_default.debug(`Removing build match for "${src}"`);let match=this.buildMatches.get(src);match&&ops.push(shutdownBuilder(match)),this.buildMatches.delete(src)}await Promise.all(ops);let blockingBuilds=[];for(let match of matches){let currentMatch=this.buildMatches.get(match.src);if(!buildMatchEquals(currentMatch,match)&&(output_manager_default.debug(`Adding build match for "${match.src}" with "${match.use}"`),this.buildMatches.set(match.src,match),!isInitial&&needsBlockingBuild(match))){let buildPromise=executeBuild(vercelConfig,this,this.files,match,null,!1);blockingBuilds.push(buildPromise)}}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_utils.isErrnoException)(err)||err.code!=="ENOENT")throw err}try{return{...this.validateEnvConfig(fileName,base||{},env)}}catch(err){if(err instanceof MissingDotenvVarsError)this.reportError(err),await this.exit();else throw err}return{}}getVercelConfig(){if(this.getVercelConfigPromise)return this.getVercelConfigPromise;this.getVercelConfigPromise=(async()=>{for(;;){let generation=this.configGeneration;try{let config=await this._getVercelConfig();if(this.stopping||generation===this.configGeneration)return config}catch(err){if(this.stopping||generation===this.configGeneration)throw err}this.functionDiscovery=void 0}})();let clear=this.clearVercelConfigPromise;return this.getVercelConfigPromise.then(clear,clear),this.getVercelConfigPromise}get devCommand(){return this.getDevCommand(this.projectSettings)}get devCommandOrigin(){return this.devProcessOrigin}getDevCommand(projectSettings){if(projectSettings?.devCommand)return projectSettings.devCommand;if(projectSettings?.framework){let frameworkSlug=projectSettings.framework,framework=import_frameworks3.frameworkList.find(f=>f.slug===frameworkSlug);if(framework){let defaults=framework.settings.devCommand.value;if(defaults)return defaults}if((0,import_build_utils9.shouldUseExperimentalBackends)(frameworkSlug))return"npx @vercel/cervel dev"}}getFunctionDiscovery(options){let key=JSON.stringify(options);if(!this.functionDiscovery||this.functionDiscovery.key!==key){let promise=collectDevFunctions(options);this.functionDiscovery={key,promise},promise.catch(()=>{this.functionDiscovery?.promise===promise&&(this.functionDiscovery=void 0)})}return this.functionDiscovery.promise}getDevFunction(outputPath){return this.functionRegistry.functions.get(outputPath)}getDevSchedules(){return this.functionRegistry.schedules}async dispatchSchedule({delivery,signal}){if(signal.throwIfAborted(),this.stopping)throw new Error("Local Schedules is stopping");if(delivery.type==="queue"){if(!this.queueBroker)throw new Error("Local Queue broker is not ready");this.queueBroker.enqueue(delivery.topic,Buffer.from(JSON.stringify(delivery.message)),"application/json");return}if(delivery.type==="path"){if(!this.devProcessOrigin)throw new Error(`Schedule path "${delivery.path}" is not ready because the dev server is unavailable`);signal.throwIfAborted();let response=await directFetch(`${this.devProcessOrigin}${delivery.path}`,{method:delivery.requestMethod,signal});if(!response.ok)throw new Error(`Schedule path "${delivery.path}" returned HTTP ${response.status}`);return}let invoke=this.resolveDevFunction(delivery.function);if(!invoke)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);signal.throwIfAborted();let onAbort=()=>{},aborted=new Promise((_,reject)=>{onAbort=()=>reject(signal.reason),signal.addEventListener("abort",onAbort,{once:!0})});try{let result=await Promise.race([aborted,invoke({method:"POST",headers:delivery.headers,body:Buffer.alloc(0),signal})]);if(!result)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);if(!result.ok)throw new Error(`Schedule function "${delivery.function}" returned HTTP ${result.status}`)}finally{signal.removeEventListener("abort",onAbort)}}resolveDevFunction(outputPath){let 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,{compileVercelConfig}=await import("../../chunks/compile-vercel-config-UQIYIVA6.js"),compiled=await compileVercelConfig(this.cwd),configPath=getLocalPathConfig(this.cwd,!!compiled.sourceFile),[pkg=null,vercelConfig={version:2,[import_client.fileNameSymbol]:"vercel.json"}]=await Promise.all([this.readJsonFile("package.json"),this.readJsonFile(configPath,!0)]);await this.validateVercelConfig(vercelConfig);let functionConfig=structuredClone(vercelConfig),sourceFiles;for(let[name,service]of Object.entries(this.queueBroker?vercelConfig.services??vercelConfig.experimentalServicesV2??{}:{}))if(Object.values(service.functions??{}).some(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,{schedules}=functionConfig,scheduleEntrypointPlan;if(!hasResolvedServices&&schedules?.some(import_schedule_entrypoint.hasScheduleEntrypointTarget)&&(sourceFiles=(await staticFiles(this.cwd,{})).map(f=>relative(this.cwd,f)),scheduleEntrypointPlan=(0,import_schedule_entrypoint.planScheduleEntrypoints)({schedules,files:sourceFiles,framework:nextProjectSettings.framework,functions:functionConfig.functions})),!vercelConfig.experimentalServices&&!hasResolvedServices&&(!vercelConfig.builds||vercelConfig.builds.length===0)){let{projectSettings,cleanUrls,trailingSlash}=vercelConfig,files=sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative(this.cwd,f));sourceFiles=files;let detectionOptions={tag:"latest",reservedFunctionFiles:scheduleEntrypointPlan?.reservedFunctionFiles,bunVersion:vercelConfig.bunVersion,functions:vercelConfig.functions,projectSettings:projectSettings||nextProjectSettings,featHandleMiss:!0,cleanUrls,trailingSlash,proxy:vercelConfig.proxy,workPath:this.cwd},detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions);for(;detectedBuilders.errors?.length===1&&detectedBuilders.errors[0].code==="unused_function";){let error2=detectedBuilders.errors[0],unmatchedTrigger=Object.entries(detectionOptions.functions??{}).find(([pattern,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_utils9.isExperimentalServiceV2);this.sidecars=await collectBuilderDevSidecars({builds:this.shouldUseServicesOrchestrator()?services.map(service=>service.builder):vercelConfig.builds??[],workPath:this.cwd,services})}scheduleEntrypointPlan&&(vercelConfig.builds??=[{src:"**",use:"@vercel/static"}],(0,import_schedule_entrypoint.assertNoScheduleEntrypointSourceConflict)(vercelConfig.builds,scheduleEntrypointPlan),vercelConfig.builds.push(...scheduleEntrypointPlan.builds));let functionBuilds=[...vercelConfig.builds??[]];Array.isArray(vercelConfig.builds)&&((this.getDevCommand(nextProjectSettings)||hasServices)&&(vercelConfig.builds=vercelConfig.builds.filter(this.shouldBuildInDev)),vercelConfig.builds.sort(sortBuilders)),vercelConfig.routes=(vercelConfig.routes||[]).filter(route=>"has"in route?(this.vercelConfigWarning||(this.vercelConfigWarning=!0,output_manager_default.warn(`The "has" property in ${vercelConfig[import_client.fileNameSymbol]} will be ignored during development. Deployments will work as expected.`)),!1):!0);let[runEnv,buildEnv]=await Promise.all([this.getLocalEnv(".env",vercelConfig.env),this.getLocalEnv(".env.build",vercelConfig.build?.env)]),allEnv={...buildEnv,...runEnv},envFromCloud=Object.keys(allEnv).length===0;if(envFromCloud){let envValues={...this.envValues};this.address.host&&(envValues.VERCEL_URL=this.address.host),allEnv={...envValues},runEnv={...envValues},buildEnv={...envValues}}runEnv.NODE_ENV??=process.env.NODE_ENV??"development",allEnv.NODE_ENV??=runEnv.NODE_ENV,runEnv.NOW_REGION="dev1",buildEnv.NOW_REGION="dev1",allEnv.NOW_REGION="dev1",allEnv.VERCEL_ENV="development",allEnv.VERCEL="1",this.projectId&&!process.env.VERCEL_PROJECT_ID&&("VERCEL_PROJECT_ID"in allEnv||(allEnv.VERCEL_PROJECT_ID=this.projectId),"VERCEL_PROJECT_ID"in runEnv||(runEnv.VERCEL_PROJECT_ID=this.projectId)),this.orgId&&!process.env.VERCEL_ORG_ID&&("VERCEL_ORG_ID"in allEnv||(allEnv.VERCEL_ORG_ID=this.orgId),"VERCEL_ORG_ID"in runEnv||(runEnv.VERCEL_ORG_ID=this.orgId)),nextProjectSettings?.autoExposeSystemEnvs&&(runEnv.VERCEL_REGION="dev1"),runEnv.VERCEL_CLI_VERSION=pkg_default.version,Object.assign(runEnv,this.getDevQueueEnv()),Object.assign(runEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(allEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(runEnv,this.getDevRuntimeCacheEnv(runEnv));let hasQueueFunctions=Object.values(functionConfig.functions??{}).some(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(scheduleEntrypointPlan&&schedules?(0,import_schedule_entrypoint.resolveScheduleEntrypointTargets)(schedules,scheduleEntrypointPlan):functionConfig.schedules,registry),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&this.scheduleBroker.validateStatic(staticSchedules)}catch(err){throw this.functionDiscovery=void 0,err}let{unmatchedPatterns}=registry;if(await this.refreshBulkRedirects(vercelConfig.bulkRedirectsPath),this.devCommandStarts.size&&await Promise.all(this.devCommandStarts),this.stopping||generation!==this.configGeneration)return vercelConfig;let restartForFunctionEnv=!!(this.devCommandEnv&&[...registry.functions.values()].some(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),vercelConfig}async refreshBulkRedirects(bulkRedirectsPath){let configPath=bulkRedirectsPath??null;if(configPath===this.bulkRedirectsLastPath&&!this.bulkRedirectsDirty)return;if(this.bulkRedirectsLastPath=configPath,this.bulkRedirectsDirty=!1,this.bulkRedirectsResolvedPath=configPath?resolveBulkRedirectsPath(this.cwd,configPath):null,!configPath){this.bulkRedirects=null,this.bulkRedirectsSignature=null;return}let signature=await getBulkRedirectsSignature(this.cwd,configPath);if(signature!==this.bulkRedirectsSignature){this.bulkRedirectsSignature=signature;try{let result=await loadBulkRedirects(this.cwd,configPath);this.bulkRedirects=result.table;for(let warning of result.warnings)output_manager_default.warn(warning);let count=result.table.size;count>0&&output_manager_default.log(`Loaded ${count} bulk ${(0,import_pluralize2.default)("redirect",count)} from ${configPath}`)}catch(err){this.bulkRedirects=null,output_manager_default.warn(`Failed to load bulk redirects from "${configPath}": ${(0,import_error_utils.errorToString)(err)}`)}}}async readJsonFile(filePath,strict=!1){let rel,abs;isAbsolute3(filePath)?(rel=path4.relative(this.cwd,filePath),abs=filePath):(rel=filePath,abs=join4(this.cwd,filePath)),output_manager_default.debug(`Reading \`${rel}\` file`);try{let raw=await import_fs_extra.default.readFile(abs,"utf8"),parsed=(0,import_json_parse_better_errors.default)(raw);return parsed[import_client.fileNameSymbol]=rel,parsed}catch(err){if(strict&&!((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT"))throw err;if((0,import_error_utils.isError)(err))(0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT"?output_manager_default.debug(`No \`${rel}\` file present`):err.name==="SyntaxError"&&output_manager_default.warn(`There is a syntax error in the \`${rel}\` file: ${err.message}`);else throw err}}async tryValidateOrExit(config,validate){let 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_utils.isErrnoException)(err))if(output_manager_default.debug(`Got listen error: ${err.code}`),err.code==="EADDRINUSE")typeof listenSpec[0]=="number"?(output_manager_default.note(`Requested port ${import_chalk2.default.yellow(String(listenSpec[0]))} is already in use`),listenSpec[0]++):(this.reportError(dev.DEV_LISTEN_ADDRESS_IN_USE({address:String(listenSpec[0])})),process.exit(1));else throw err;else throw err}}if(this.stopping)return;this._address=new URL2(replaceLocalhost(address)),this.runtimeCache=new RuntimeCacheStore;let devCommandPorts=this.devCommandPort?[this.devCommandPort]:[],runtimeCacheListener=await(this.listenerStartup=listenOnDevResourcePort(this.runtimeCacheServer,{name:"Runtime Cache",flag:"--runtime-cache-port",defaultPort:DEV_RUNTIME_CACHE_DEFAULT_PORT,port:this.runtimeCachePort,reservedPorts:[this.queuePort,this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT,...devCommandPorts].filter(port=>port!==void 0&&port!==0)}));if(this.stopping)return;this.runtimeCacheOrigin=runtimeCacheListener.origin,runtimeCacheListener.defaultPort!==void 0&&output_manager_default.warn(`Runtime Cache default port ${runtimeCacheListener.defaultPort} is unavailable; listening on ${runtimeCacheListener.port} instead.
|
|
42
|
+
Please ensure that ${cmd(err.path)} is properly installed`,err.link="https://vercel.link/command-not-found"),output_manager_default.prettyError(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}if(devServerResult){requestId=generateRequestId(this.podId,!0);let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown),persistent||res.once("close",()=>{this.killBuilderDevServer(pid)}),debug(`Proxying to "${builderPkg.name}" dev server (port=${port}, pid=${pid})`);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search});let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,`http://127.0.0.1:${port}`,this,requestId,!1)}else debug(`Skipping \`startDevServer()\` for ${match.entrypoint}`)}let foundAsset=findAsset(match,requestPath,vercelConfig);if(!foundAsset&&callLevel===0&&(await this.triggerBuild(match,buildRequestPath,req,vercelConfig),foundAsset=findAsset(match,requestPath,vercelConfig)),this.devProcessOrigin&&(!foundAsset||foundAsset&&foundAsset.asset.type!=="Lambda")){debug("Proxying to frontend dev server");let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,this.devProcessOrigin,this,requestId,!1)}if(!foundAsset){await this.send404(req,res,requestId);return}let{asset,assetKey}=foundAsset;switch(debug(`Serving asset: [${asset.type}] ${assetKey} ${asset.contentType||""}`),asset.type){case"FileFsRef":this.setResponseHeaders(res,requestId);let staticResHeaders={};applyResponseTransforms(staticResHeaders,responseTransforms??[]);for(let[name,value]of Object.entries(staticResHeaders))value!==void 0&&res.setHeader(name,value);return req.url=`/${basename(asset.fsPath)}`,serveStaticFile(req,res,dirname3(asset.fsPath),{headers:[{source:"**/*",headers:[{key:"Content-Type",value:asset.contentType||getMimeType(assetKey)}]}]});case"FileBlob":let headers2={"Content-Length":asset.data.length,"Content-Type":asset.contentType||getMimeType(assetKey)};applyResponseTransforms(headers2,responseTransforms??[]),this.setResponseHeaders(res,requestId,headers2),res.end(asset.data);return;case"Lambda":if(!asset.fn){await this.sendError(req,res,requestId,"INTERNAL_LAMBDA_NOT_FOUND");return}requestId=generateRequestId(this.podId,!0);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search}),applyRequestTransforms(req,requestTransforms);let path6=req.url||"/",body=await(0,import_raw_body2.default)(req);debug(`Invoking lambda: "${assetKey}" with ${path6}`);let result;try{result=await this.invokeBuiltLambda(asset,req,requestId,body)}catch(err){console.error(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}statusCode||(res.statusCode=result.statusCode);let lambdaHeaders=result.headers??{};applyResponseTransforms(lambdaHeaders,responseTransforms??[]),this.setResponseHeaders(res,requestId,lambdaHeaders);let resBody;return result.encoding==="base64"&&typeof result.body=="string"?resBody=Buffer.from(result.body,"base64"):resBody=result.body,res.end(resBody);default:await this.sendError(req,res,requestId,"UNKNOWN_ASSET_TYPE")}};if(this.cwd=cwd,this.repoRoot=options.repoRoot??cwd,this.envConfigs={buildEnv:{},runEnv:{},allEnv:{}},this.envValues=options.envValues||{},this.projectId=options.projectId,this.orgId=options.orgId,this.queuePort=options.queuePort,this.runtimeCachePort=options.runtimeCachePort,this.schedulesPort=options.schedulesPort,this.routing=options.routing??!0,this.devCommandPort=options.devCommandPort,!this.routing&&!this.devCommandPort)throw new Error("Running without the router needs a `devCommandPort`");this.scheduleBroker=new import_local_schedules2.ScheduleBroker({ownerId:this.orgId??"team_local",projectId:this.projectId??"prj_local",trackId:"development",dispatch:invocation=>this.dispatchSchedule(invocation),onError:(err,invocation)=>{try{output_manager_default.error(`Failed to dispatch schedule "${invocation.schedule.name}": ${(0,import_error_utils.errorToString)(err)}`)}catch{}}}),this.resourceProxyToken=randomBytes2(32).toString("base64url"),this.reportError=createErrorReporter2(code=>options.onErrorCode?.(code)),this.files={},this.originalProjectSettings=options.projectSettings,this.projectSettings=options.projectSettings,this.services=options.services,this.useImplicitServicesEnvInjection=options.useImplicitServicesEnvInjection??!0,this.caseSensitive=!1,this.apiDir=null,this.apiExtensions=new Set,this.proxy=import_http_proxy_node16.default.createProxyServer({changeOrigin:!0,ws:!0,xfwd:!0}),this.proxy.on("proxyRes",(proxyRes,req)=>{proxyRes.headers.server="Vercel";let responseTransforms=this.responseTransformsByReq.get(req);responseTransforms&&(this.responseTransformsByReq.delete(req),applyResponseTransforms(proxyRes.headers,responseTransforms))}),this.proxy.on("error",(err,req,res)=>{if(output_manager_default.debug(`Proxy error for ${req?.url??"unknown request"}: ${(0,import_error_utils.errorToString)(err)}`),!!res){if("destroy"in res&&typeof res.destroy=="function"){res.destroy();return}res instanceof http.ServerResponse&&(res.headersSent||res.writeHead(502),res.end())}}),this.server=http.createServer(this.devServerHandler),this.server.timeout=0,this.queueServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.queueOrigin,this.handleQueuesRoute)}),this.runtimeCacheServer=http.createServer((req,res)=>{this.handleResourceServerRequest(req,res,this.runtimeCacheOrigin,this.handleRuntimeCacheRoute)}),this.schedulesServer=http.createServer((req,res)=>{this.schedulesSession&&res.setHeader(LOCAL_SCHEDULES_SESSION_HEADER,this.schedulesSession.session.id),this.handleResourceServerRequest(req,res,this.schedulesOrigin,this.handleSchedulesRoute)}),this.stopping=!1,this.buildMatches=new Map,this.inProgressBuilds=new Map,this.devCacheDir=join4(getVercelDirectory(cwd),"cache"),this.vercelConfigWarning=!1,this.getVercelConfigPromise=null,this.blockingBuildsPromise=null,this.startPromise=null,this.bulkRedirects=null,this.bulkRedirectsSignature=null,this.bulkRedirectsLastPath=null,this.bulkRedirectsResolvedPath=null,this.bulkRedirectsDirty=!0,this.watchAggregationId=null,this.watchAggregationEvents=[],this.watchAggregationTimeout=500,this.filter=path6=>!!path6,this.podId=Math.random().toString(32).slice(-5),this.shutdownCallbacks=new Map}get address(){if(!this._address)throw dev.DEV_INTERNAL_ADDRESS_UNAVAILABLE();return this._address}shouldUseServicesOrchestrator(){return!!(this.services&&this.services.length>0)}hasSubscribers(){return!!this.sidecars?.length}getDevQueueEnv(){return this.queueOrigin?getDevQueueEnv(this.queueOrigin,this.hasSubscribers()):{}}getDevRuntimeCacheEnv(env){return!this.runtimeCacheOrigin||env.RUNTIME_CACHE_ENDPOINT?{}:process.env.RUNTIME_CACHE_ENDPOINT?{RUNTIME_CACHE_ENDPOINT:process.env.RUNTIME_CACHE_ENDPOINT,...process.env.RUNTIME_CACHE_HEADERS?{RUNTIME_CACHE_HEADERS:process.env.RUNTIME_CACHE_HEADERS}:{}}:getDevRuntimeCacheEnv(this.runtimeCacheOrigin,DEV_RUNTIME_CACHE_API_PREFIX)}get resourceEndpoints(){if(!this.queueOrigin||!this.runtimeCacheOrigin)throw new Error("Local resource servers have not started");let proxied=(direct,path6)=>this.routing?`${this.address.origin}${path6}`:direct,runtimeCache=`${this.runtimeCacheOrigin}${DEV_RUNTIME_CACHE_API_PREFIX}`;return{queues:{direct:this.queueOrigin,proxy:proxied(this.queueOrigin,`${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`)},runtimeCache:{direct:runtimeCache,proxy:proxied(runtimeCache,`${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}${DEV_RUNTIME_CACHE_API_PREFIX}`)},...this.schedulesOrigin?{schedules:{direct:this.schedulesOrigin,proxy:proxied(this.schedulesOrigin,`${DEV_SCHEDULES_PROXY_PREFIX}/${this.resourceProxyToken}`)}}:{}}}getDevResourceMeta(){return{devResourceEndpoints:this.resourceEndpoints}}handleResourceServerRequest(req,res,origin,handler){if(!origin||!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}if(!isValidDevResourceHost(origin,req.headers.host)){res.writeHead(403),res.end("Forbidden");return}let pathname=new URL2(req.url||"/","http://127.0.0.1").pathname;handler(req,res,pathname).catch(err=>{output_manager_default.debug(`Local resource request failed for ${req.url||"/"}: ${(0,import_error_utils.errorToString)(err)}`),res.headersSent||res.writeHead(500),res.end("Internal Server Error")})}isAuthorizedResourceRequest(req,token){let authorization=req.headers.authorization;if(typeof authorization!="string")return!1;let encoder=new TextEncoder,actual=encoder.encode(authorization),expected=encoder.encode(`Bearer ${token}`);return actual.length===expected.length&&timingSafeEqual(actual,expected)}getBuilderDevEnv(match,env){let result={...env,...getDevSchedulesEnv(this.schedulesOrigin)};if(match.builderWithPkg.pkg.name!=="@vercel/container")return result;let endpoints=this.resourceEndpoints;return Object.assign(result,getDevSchedulesEnv(endpoints.schedules?.proxy,!0)),result.VERCEL_QUEUE_BASE_URL===endpoints.queues.direct&&Object.assign(result,getDevQueueEnv(endpoints.queues.proxy,result.VERCEL_HAS_WORKER_SERVICES!==void 0)),result.RUNTIME_CACHE_ENDPOINT===endpoints.runtimeCache.direct&&Object.assign(result,getDevRuntimeCacheEnv(endpoints.runtimeCache.proxy,"")),result}getSidecarDevMeta(match){let serviceCount=(this.sidecars??[]).filter(sidecar=>sidecar.builder.use!==match.use?!1:!sidecar.workspace||sidecar.workspace===".").length;return serviceCount>0?{serviceCount}:{}}async setupBuilderDevSidecars(){if(this.shouldUseServicesOrchestrator())return;let sidecars=this.sidecars??[];if(sidecars.length===0)return;Object.assign(this.envConfigs.runEnv,this.getDevQueueEnv());let services=sidecars.map(toOrchestratorService),orchestrator=new ServicesOrchestrator({services,cwd:this.cwd,repoRoot:this.repoRoot,env:this.envConfigs.allEnv,proxyOrigin:this.address.origin,resourceEndpoints:this.resourceEndpoints,useImplicitEnvInjection:!1,preferServiceBuilder:!0,onQueueSubscriptions:(serviceName,subscriptions)=>this.queueBroker?.updateServiceSubscriptions(serviceName,subscriptions)});this.sidecarOrchestrator=orchestrator,this.queueBroker?.registerServices(services);try{await orchestrator.startAll()}catch(err){throw await orchestrator.stopAll(),this.sidecarOrchestrator=void 0,this.sidecars=[],err}output_manager_default.log(`Started ${sidecars.length} development ${(0,import_pluralize2.default)("sidecar",sidecars.length)}`)}async exit(code=1){await this.stop(code),process.exit(code)}enqueueFsEvent(type,path6){this.bulkRedirectsResolvedPath&&(path6===this.bulkRedirectsResolvedPath||path6.startsWith(this.bulkRedirectsResolvedPath+sep2))&&(this.bulkRedirectsDirty=!0),this.watchAggregationEvents.push({type,path:path6}),this.watchAggregationId===null&&(this.watchAggregationId=setTimeout(()=>{let events=this.watchAggregationEvents.slice();this.watchAggregationEvents.length=0,this.watchAggregationId=null,this.handleFilesystemEvents(events).catch(err=>{output_manager_default.prettyError(err),(0,import_error_utils.isError)(err)&&typeof err.stack=="string"&&output_manager_default.debug(err.stack)})},this.watchAggregationTimeout))}async handleFilesystemEvents(events){if(this.stopping)return;output_manager_default.debug(`Filesystem watcher notified of ${events.length} events`);let filesChanged=new Set,filesRemoved=new Set,distPaths=[];for(let buildMatch of this.buildMatches.values())for(let buildResult of buildMatch.buildResults.values())buildResult.distPath&&distPaths.push(buildResult.distPath);if(events=events.filter(event=>distPaths.every(distPath=>!event.path.startsWith(distPath))),events.length!==0){this.functionReconciliations++;try{this.configGeneration++,this.functionDiscovery=void 0;for(let event of events)event.type==="add"?await this.handleFileCreated(event.path,filesChanged,filesRemoved):event.type==="unlink"?this.handleFileDeleted(event.path,filesChanged,filesRemoved):event.type==="change"&&await this.handleFileModified(event.path,filesChanged,filesRemoved);let vercelConfig=await this.getVercelConfig();if(this.stopping)return;await this.updateBuildMatches(vercelConfig);let filesChangedArray=[...filesChanged],filesRemovedArray=[...filesRemoved],needsRebuild=new Map;for(let match of this.buildMatches.values()){this.canonicalizeFunctionBuild(match);for(let[requestPath,result]of match.buildResults)if(!needsRebuild.has(result)&&Array.isArray(result.watch)){for(let pattern of result.watch)if(minimatches(filesChangedArray,pattern)||minimatches(filesRemovedArray,pattern)){needsRebuild.set(result,[requestPath,match]);break}}}if(needsRebuild.size>0){output_manager_default.debug(`Triggering ${needsRebuild.size} rebuilds`),filesChangedArray.length>0&&output_manager_default.debug(`Files changed: ${filesChangedArray.join(", ")}`),filesRemovedArray.length>0&&output_manager_default.debug(`Files removed: ${filesRemovedArray.join(", ")}`);for(let[result,[requestPath,match]]of needsRebuild)requestPath===null||await shouldServe(match,this.files,requestPath,this,vercelConfig)?this.triggerBuild(match,requestPath,null,vercelConfig,result,filesChangedArray,filesRemovedArray).catch(err=>{output_manager_default.warn(`An error occurred while rebuilding \`${match.src}\`:`),console.error(err.stack)}):output_manager_default.debug(`Not rebuilding because \`shouldServe()\` returned \`false\` for "${match.use}" request path "${requestPath}"`)}}finally{this.functionReconciliations--}}}async handleFileCreated(fsPath,changed,removed){let name=relative(this.cwd,fsPath);try{await this.getVercelConfig(),this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath});let extensionless=this.getExtensionlessFile(name);extensionless&&(this.files[extensionless]=await import_build_utils9.FileFsRef.fromFsPath({fsPath})),fileChanged(name,changed,removed),output_manager_default.debug(`File created: ${name}`)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File created, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}handleFileDeleted(fsPath,changed,removed){let name=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_utils9.FileFsRef.fromFsPath({fsPath}),fileChanged(name,changed,removed),output_manager_default.debug(`File modified: ${name}`)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File modified, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}async updateBuildMatches(vercelConfig,isInitial=!1){let fileList=this.resolveBuildFiles(this.files),matches=await getBuildMatches(vercelConfig,this.cwd,this,fileList),sources=matches.map(m=>m.src);isInitial&&fileList.length===0&&output_manager_default.warn("There are no files inside your deployment.");let ops=[];for(let src of this.buildMatches.keys())if(!sources.includes(src)){output_manager_default.debug(`Removing build match for "${src}"`);let match=this.buildMatches.get(src);match&&ops.push(shutdownBuilder(match)),this.buildMatches.delete(src)}await Promise.all(ops);let blockingBuilds=[];for(let match of matches){let currentMatch=this.buildMatches.get(match.src);if(!buildMatchEquals(currentMatch,match)&&(output_manager_default.debug(`Adding build match for "${match.src}" with "${match.use}"`),this.buildMatches.set(match.src,match),!isInitial&&needsBlockingBuild(match))){let buildPromise=executeBuild(vercelConfig,this,this.files,match,null,!1);blockingBuilds.push(buildPromise)}}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_utils.isErrnoException)(err)||err.code!=="ENOENT")throw err}try{return{...this.validateEnvConfig(fileName,base||{},env)}}catch(err){if(err instanceof MissingDotenvVarsError)this.reportError(err),await this.exit();else throw err}return{}}getVercelConfig(){if(this.getVercelConfigPromise)return this.getVercelConfigPromise;this.getVercelConfigPromise=(async()=>{for(;;){let generation=this.configGeneration;try{let config=await this._getVercelConfig();if(this.stopping||generation===this.configGeneration)return config}catch(err){if(this.stopping||generation===this.configGeneration)throw err}this.functionDiscovery=void 0}})();let clear=this.clearVercelConfigPromise;return this.getVercelConfigPromise.then(clear,clear),this.getVercelConfigPromise}get devCommand(){return this.getDevCommand(this.projectSettings)}get devCommandOrigin(){return this.devProcessOrigin}getDevCommand(projectSettings){if(projectSettings?.devCommand)return projectSettings.devCommand;if(projectSettings?.framework){let frameworkSlug=projectSettings.framework,framework=import_frameworks3.frameworkList.find(f=>f.slug===frameworkSlug);if(framework){let defaults=framework.settings.devCommand.value;if(defaults)return defaults}if((0,import_build_utils9.shouldUseExperimentalBackends)(frameworkSlug))return"npx @vercel/cervel dev"}}getFunctionDiscovery(options){let key=JSON.stringify(options);if(!this.functionDiscovery||this.functionDiscovery.key!==key){let promise=collectDevFunctions(options);this.functionDiscovery={key,promise},promise.catch(()=>{this.functionDiscovery?.promise===promise&&(this.functionDiscovery=void 0)})}return this.functionDiscovery.promise}getDevFunction(outputPath){return this.functionRegistry.functions.get(outputPath)}getDevSchedules(){return this.functionRegistry.schedules}async dispatchSchedule({delivery,signal}){if(signal.throwIfAborted(),this.stopping)throw new Error("Local Schedules is stopping");if(delivery.type==="queue"){if(!this.queueBroker)throw new Error("Local Queue broker is not ready");this.queueBroker.enqueue(delivery.topic,Buffer.from(JSON.stringify(delivery.message)),"application/json");return}if(delivery.type==="path"){if(!this.devProcessOrigin)throw new Error(`Schedule path "${delivery.path}" is not ready because the dev server is unavailable`);signal.throwIfAborted();let response=await directFetch(`${this.devProcessOrigin}${delivery.path}`,{method:delivery.requestMethod,signal});if(!response.ok)throw new Error(`Schedule path "${delivery.path}" returned HTTP ${response.status}`);return}let invoke=this.resolveDevFunction(delivery.function);if(!invoke)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);signal.throwIfAborted();let onAbort=()=>{},aborted=new Promise((_,reject)=>{onAbort=()=>reject(signal.reason),signal.addEventListener("abort",onAbort,{once:!0})});try{let result=await Promise.race([aborted,invoke({method:"POST",headers:delivery.headers,body:Buffer.alloc(0),signal})]);if(!result)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);if(!result.ok)throw new Error(`Schedule function "${delivery.function}" returned HTTP ${result.status}`)}finally{signal.removeEventListener("abort",onAbort)}}resolveDevFunction(outputPath){let 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,{compileVercelConfig}=await import("../../chunks/compile-vercel-config-ZY34MDLE.js"),compiled=await compileVercelConfig(this.cwd),configPath=getLocalPathConfig(this.cwd,!!compiled.sourceFile),[pkg=null,vercelConfig={version:2,[import_client.fileNameSymbol]:"vercel.json"}]=await Promise.all([this.readJsonFile("package.json"),this.readJsonFile(configPath,!0)]);await this.validateVercelConfig(vercelConfig);let functionConfig=structuredClone(vercelConfig),sourceFiles;for(let[name,service]of Object.entries(this.queueBroker?vercelConfig.services??vercelConfig.experimentalServicesV2??{}:{}))if(Object.values(service.functions??{}).some(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,{schedules}=functionConfig,scheduleEntrypointPlan;if(!hasResolvedServices&&schedules?.some(import_schedule_entrypoint.hasScheduleEntrypointTarget)&&(sourceFiles=(await staticFiles(this.cwd,{})).map(f=>relative(this.cwd,f)),scheduleEntrypointPlan=(0,import_schedule_entrypoint.planScheduleEntrypoints)({schedules,files:sourceFiles,framework:nextProjectSettings.framework,functions:functionConfig.functions})),!vercelConfig.experimentalServices&&!hasResolvedServices&&(!vercelConfig.builds||vercelConfig.builds.length===0)){let{projectSettings,cleanUrls,trailingSlash}=vercelConfig,files=sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative(this.cwd,f));sourceFiles=files;let detectionOptions={tag:"latest",reservedFunctionFiles:scheduleEntrypointPlan?.reservedFunctionFiles,bunVersion:vercelConfig.bunVersion,functions:vercelConfig.functions,projectSettings:projectSettings||nextProjectSettings,featHandleMiss:!0,cleanUrls,trailingSlash,proxy:vercelConfig.proxy,workPath:this.cwd},detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions);for(;detectedBuilders.errors?.length===1&&detectedBuilders.errors[0].code==="unused_function";){let error2=detectedBuilders.errors[0],unmatchedTrigger=Object.entries(detectionOptions.functions??{}).find(([pattern,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_utils9.isExperimentalServiceV2);this.sidecars=await collectBuilderDevSidecars({builds:this.shouldUseServicesOrchestrator()?services.map(service=>service.builder):vercelConfig.builds??[],workPath:this.cwd,services})}scheduleEntrypointPlan&&(vercelConfig.builds??=[{src:"**",use:"@vercel/static"}],(0,import_schedule_entrypoint.assertNoScheduleEntrypointSourceConflict)(vercelConfig.builds,scheduleEntrypointPlan),vercelConfig.builds.push(...scheduleEntrypointPlan.builds));let functionBuilds=[...vercelConfig.builds??[]];Array.isArray(vercelConfig.builds)&&((this.getDevCommand(nextProjectSettings)||hasServices)&&(vercelConfig.builds=vercelConfig.builds.filter(this.shouldBuildInDev)),vercelConfig.builds.sort(sortBuilders)),vercelConfig.routes=(vercelConfig.routes||[]).filter(route=>"has"in route?(this.vercelConfigWarning||(this.vercelConfigWarning=!0,output_manager_default.warn(`The "has" property in ${vercelConfig[import_client.fileNameSymbol]} will be ignored during development. Deployments will work as expected.`)),!1):!0);let[runEnv,buildEnv]=await Promise.all([this.getLocalEnv(".env",vercelConfig.env),this.getLocalEnv(".env.build",vercelConfig.build?.env)]),allEnv={...buildEnv,...runEnv},envFromCloud=Object.keys(allEnv).length===0;if(envFromCloud){let envValues={...this.envValues};this.address.host&&(envValues.VERCEL_URL=this.address.host),allEnv={...envValues},runEnv={...envValues},buildEnv={...envValues}}runEnv.NODE_ENV??=process.env.NODE_ENV??"development",allEnv.NODE_ENV??=runEnv.NODE_ENV,runEnv.NOW_REGION="dev1",buildEnv.NOW_REGION="dev1",allEnv.NOW_REGION="dev1",allEnv.VERCEL_ENV="development",allEnv.VERCEL="1",this.projectId&&!process.env.VERCEL_PROJECT_ID&&("VERCEL_PROJECT_ID"in allEnv||(allEnv.VERCEL_PROJECT_ID=this.projectId),"VERCEL_PROJECT_ID"in runEnv||(runEnv.VERCEL_PROJECT_ID=this.projectId)),this.orgId&&!process.env.VERCEL_ORG_ID&&("VERCEL_ORG_ID"in allEnv||(allEnv.VERCEL_ORG_ID=this.orgId),"VERCEL_ORG_ID"in runEnv||(runEnv.VERCEL_ORG_ID=this.orgId)),nextProjectSettings?.autoExposeSystemEnvs&&(runEnv.VERCEL_REGION="dev1"),runEnv.VERCEL_CLI_VERSION=pkg_default.version,Object.assign(runEnv,this.getDevQueueEnv()),Object.assign(runEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(allEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(runEnv,this.getDevRuntimeCacheEnv(runEnv));let hasQueueFunctions=Object.values(functionConfig.functions??{}).some(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(scheduleEntrypointPlan&&schedules?(0,import_schedule_entrypoint.resolveScheduleEntrypointTargets)(schedules,scheduleEntrypointPlan):functionConfig.schedules,registry),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&this.scheduleBroker.validateStatic(staticSchedules)}catch(err){throw this.functionDiscovery=void 0,err}let{unmatchedPatterns}=registry;if(await this.refreshBulkRedirects(vercelConfig.bulkRedirectsPath),this.devCommandStarts.size&&await Promise.all(this.devCommandStarts),this.stopping||generation!==this.configGeneration)return vercelConfig;let restartForFunctionEnv=!!(this.devCommandEnv&&[...registry.functions.values()].some(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),vercelConfig}async refreshBulkRedirects(bulkRedirectsPath){let configPath=bulkRedirectsPath??null;if(configPath===this.bulkRedirectsLastPath&&!this.bulkRedirectsDirty)return;if(this.bulkRedirectsLastPath=configPath,this.bulkRedirectsDirty=!1,this.bulkRedirectsResolvedPath=configPath?resolveBulkRedirectsPath(this.cwd,configPath):null,!configPath){this.bulkRedirects=null,this.bulkRedirectsSignature=null;return}let signature=await getBulkRedirectsSignature(this.cwd,configPath);if(signature!==this.bulkRedirectsSignature){this.bulkRedirectsSignature=signature;try{let result=await loadBulkRedirects(this.cwd,configPath);this.bulkRedirects=result.table;for(let warning of result.warnings)output_manager_default.warn(warning);let count=result.table.size;count>0&&output_manager_default.log(`Loaded ${count} bulk ${(0,import_pluralize2.default)("redirect",count)} from ${configPath}`)}catch(err){this.bulkRedirects=null,output_manager_default.warn(`Failed to load bulk redirects from "${configPath}": ${(0,import_error_utils.errorToString)(err)}`)}}}async readJsonFile(filePath,strict=!1){let rel,abs;isAbsolute3(filePath)?(rel=path4.relative(this.cwd,filePath),abs=filePath):(rel=filePath,abs=join4(this.cwd,filePath)),output_manager_default.debug(`Reading \`${rel}\` file`);try{let raw=await import_fs_extra.default.readFile(abs,"utf8"),parsed=(0,import_json_parse_better_errors.default)(raw);return parsed[import_client.fileNameSymbol]=rel,parsed}catch(err){if(strict&&!((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT"))throw err;if((0,import_error_utils.isError)(err))(0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT"?output_manager_default.debug(`No \`${rel}\` file present`):err.name==="SyntaxError"&&output_manager_default.warn(`There is a syntax error in the \`${rel}\` file: ${err.message}`);else throw err}}async tryValidateOrExit(config,validate){let 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_utils.isErrnoException)(err))if(output_manager_default.debug(`Got listen error: ${err.code}`),err.code==="EADDRINUSE")typeof listenSpec[0]=="number"?(output_manager_default.note(`Requested port ${import_chalk2.default.yellow(String(listenSpec[0]))} is already in use`),listenSpec[0]++):(this.reportError(dev.DEV_LISTEN_ADDRESS_IN_USE({address:String(listenSpec[0])})),process.exit(1));else throw err;else throw err}}if(this.stopping)return;this._address=new URL2(replaceLocalhost(address)),this.runtimeCache=new RuntimeCacheStore;let devCommandPorts=this.devCommandPort?[this.devCommandPort]:[],runtimeCacheListener=await(this.listenerStartup=listenOnDevResourcePort(this.runtimeCacheServer,{name:"Runtime Cache",flag:"--runtime-cache-port",defaultPort:DEV_RUNTIME_CACHE_DEFAULT_PORT,port:this.runtimeCachePort,reservedPorts:[this.queuePort,this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT,...devCommandPorts].filter(port=>port!==void 0&&port!==0)}));if(this.stopping)return;this.runtimeCacheOrigin=runtimeCacheListener.origin,runtimeCacheListener.defaultPort!==void 0&&output_manager_default.warn(`Runtime Cache default port ${runtimeCacheListener.defaultPort} is unavailable; listening on ${runtimeCacheListener.port} instead.
|
|
43
43
|
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.
|
|
44
44
|
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.
|
|
45
45
|
Pin a port with --schedules-port for clients outside the dev server.
|