vercel 63.0.2 → 63.1.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-QKGWNVQS.js → add-CCFBYKZH.js} +1 -1
- package/dist/chunks/{add-BODUK747.js → add-FNCCXJZO.js} +1 -1
- package/dist/chunks/{add-QBGY56BR.js → add-LU5TSLJU.js} +1 -1
- package/dist/chunks/{build-SD6SLRK7.js → build-PUIFBQKZ.js} +1 -1
- package/dist/chunks/{chunk-MEJTHWZB.js → chunk-36EFWYTN.js} +1 -1
- package/dist/chunks/{chunk-JUSQYKFF.js → chunk-3TJDVDDJ.js} +1 -1
- package/dist/chunks/{chunk-QW2UP4W4.js → chunk-3YQVBYQD.js} +1 -1
- package/dist/chunks/{chunk-7D2HVBVP.js → chunk-5O2CW3SX.js} +1 -1
- package/dist/chunks/chunk-5YQP44VL.js +10 -0
- package/dist/chunks/{chunk-KNBEUC4P.js → chunk-6BE4D57F.js} +1 -1
- package/dist/chunks/{chunk-HJ3NY4UA.js → chunk-6LXX5P3A.js} +1 -1
- package/dist/chunks/{chunk-64U5W6GU.js → chunk-6OUBLFZ2.js} +1 -1
- package/dist/chunks/{chunk-YLTCVZOL.js → chunk-6TEFVB2U.js} +1 -1
- package/dist/chunks/{chunk-3AF3TTCR.js → chunk-7SGM233C.js} +1 -1
- package/dist/chunks/{chunk-PSBBSY46.js → chunk-A6RRKSD3.js} +1 -1
- package/dist/chunks/{chunk-ESMQCFCX.js → chunk-AHSMFZWH.js} +1 -1
- package/dist/chunks/{chunk-TKA7PPGY.js → chunk-BIFAR2CO.js} +1 -1
- package/dist/chunks/{chunk-X3JK3SQ2.js → chunk-D7KEDMBF.js} +1 -1
- package/dist/chunks/{chunk-6LRVRPYO.js → chunk-E6UKNYFF.js} +1 -1
- package/dist/chunks/{chunk-NZBUIMZG.js → chunk-EDVP7QUI.js} +1 -1
- package/dist/chunks/{chunk-WF5YVWWY.js → chunk-FU7KGU6V.js} +1 -1
- package/dist/chunks/{chunk-IYL5CKZ4.js → chunk-GAG42XNF.js} +1 -1
- package/dist/chunks/{chunk-DZ6GORJ7.js → chunk-HWYHRPWP.js} +1 -1
- package/dist/chunks/{chunk-UTW2FDSC.js → chunk-I3D36ZLJ.js} +1 -1
- package/dist/chunks/{chunk-KTNRWBHM.js → chunk-I7FGFRN3.js} +1 -1
- package/dist/chunks/{chunk-MA4K5IWW.js → chunk-IFNTXDX2.js} +1 -1
- package/dist/chunks/{chunk-JTAAWOJS.js → chunk-IMC63GXI.js} +1 -1
- package/dist/chunks/{chunk-VIBUYIZ3.js → chunk-J2LAZELI.js} +1 -1
- package/dist/chunks/{chunk-SY4EANZH.js → chunk-JORUFFOD.js} +3 -3
- package/dist/chunks/{chunk-4A5SGLIH.js → chunk-JYFYL3ON.js} +1 -1
- package/dist/chunks/{chunk-IAUAFUO2.js → chunk-K5GYV5CW.js} +1 -1
- package/dist/chunks/{chunk-B3PZ3I4Z.js → chunk-KCQERNQX.js} +1 -1
- package/dist/chunks/{chunk-QZRZ6ECD.js → chunk-KG3OGJ3U.js} +1 -1
- package/dist/chunks/{chunk-2H243SJV.js → chunk-MSH7V3FL.js} +1 -1
- package/dist/chunks/{chunk-VNSQCAVT.js → chunk-MT4MO7DT.js} +1 -1
- package/dist/chunks/{chunk-XJOOPPSQ.js → chunk-NUITF4GR.js} +1 -1
- package/dist/chunks/chunk-OB5XGIDM.js +9 -0
- package/dist/chunks/{chunk-25S4PQNK.js → chunk-OPVNMCAF.js} +1 -1
- package/dist/chunks/{chunk-AZ76R3LW.js → chunk-PLG4UIV4.js} +1 -1
- package/dist/chunks/{chunk-CRO7VQWK.js → chunk-PR7SYJVT.js} +1 -1
- package/dist/chunks/{chunk-2WYDLP7X.js → chunk-R6OWQQMZ.js} +1 -1
- package/dist/chunks/{chunk-SSEVYTJ7.js → chunk-RIPCUZO6.js} +1 -1
- package/dist/chunks/{chunk-VJEQAITW.js → chunk-RV77ZW7T.js} +1 -1
- package/dist/chunks/{chunk-V2BKSCXI.js → chunk-SKTP7MSL.js} +1 -1
- package/dist/chunks/{chunk-MYMM34ZH.js → chunk-SWJYZETA.js} +4 -4
- package/dist/chunks/{chunk-BZYQ6RFV.js → chunk-SYEKOJHT.js} +1 -1
- package/dist/chunks/{chunk-VOB4W7DO.js → chunk-SZRSBECO.js} +1 -1
- package/dist/chunks/{chunk-2LGNEOKV.js → chunk-T3PAZMDW.js} +1 -1
- package/dist/chunks/{chunk-V336CYEI.js → chunk-T6GXMIXO.js} +1 -1
- package/dist/chunks/{chunk-HUJPGK7W.js → chunk-TNZMCRAP.js} +1 -1
- package/dist/chunks/chunk-TUJ3WXOZ.js +7 -0
- package/dist/chunks/{chunk-BRUTDRAQ.js → chunk-VLSSMFTF.js} +1 -1
- package/dist/chunks/{chunk-VSE5BAPP.js → chunk-WPQN5UKR.js} +1 -1
- package/dist/chunks/{chunk-3DMY3OJR.js → chunk-X5GP2FBT.js} +1 -1
- package/dist/chunks/{chunk-AUZEOUZU.js → chunk-XKDY4OFQ.js} +1 -1
- package/dist/chunks/{chunk-H7LHZZKU.js → chunk-Y35RMGOU.js} +1 -1
- package/dist/chunks/{chunk-AZULOP7M.js → chunk-YIIPBH2D.js} +2 -2
- package/dist/chunks/{chunk-T6SFC3IH.js → chunk-Z6HYEIYV.js} +1 -1
- package/dist/chunks/{chunk-BWY67LI6.js → chunk-ZH4DW3T3.js} +1 -1
- package/dist/chunks/{chunk-T76ITV65.js → chunk-ZQBMRI57.js} +2 -2
- package/dist/chunks/{clear-PYDGQBSS.js → clear-E6TSPA67.js} +1 -1
- package/dist/chunks/{compile-vercel-config-KWSIFONF.js → compile-vercel-config-2HBWORW5.js} +1 -1
- package/dist/chunks/{config-Y3JEZPVK.js → config-MTH57FUD.js} +1 -1
- package/dist/chunks/{config-6TQFY5DN.js → config-NWNQSZNZ.js} +1 -1
- package/dist/chunks/{connect-git-provider-HW23GK35.js → connect-git-provider-VJYXBRYG.js} +1 -1
- package/dist/chunks/{delete-ZISJ7HIW.js → delete-MZ4LAS3L.js} +1 -1
- package/dist/chunks/{delete-HAOLSE35.js → delete-NIPKCWUT.js} +1 -1
- package/dist/chunks/{detect-services-22KZAGH2.js → detect-services-5CVG24CL.js} +1 -1
- package/dist/chunks/{disable-ZCEEK2BD.js → disable-YZATFLNR.js} +1 -1
- package/dist/chunks/{discard-VHO5BXYN.js → discard-B5IFVCDR.js} +1 -1
- package/dist/chunks/{edit-ZPNWEZWU.js → edit-3PKYF5FY.js} +1 -1
- package/dist/chunks/{edit-JRYFZ5N5.js → edit-EDTBD7PX.js} +1 -1
- package/dist/chunks/{enable-USQVAN4K.js → enable-AKGADEKU.js} +1 -1
- package/dist/chunks/{export-H7YV6NVF.js → export-NKCN63SF.js} +1 -1
- package/dist/chunks/{future-PHRPWAVY.js → future-AQR2QP74.js} +1 -1
- package/dist/chunks/{generate-cert-for-deploy-WLYVWTBG.js → generate-cert-for-deploy-UNRGDROB.js} +1 -1
- package/dist/chunks/{image-6KIQRC65.js → image-IQJVHHAW.js} +1 -1
- package/dist/chunks/{import-builders-YAC6UE33.js → import-builders-4K4WE66I.js} +1 -1
- package/dist/chunks/{inspect-MRJ6JO7M.js → inspect-2UUTLI4H.js} +1 -1
- package/dist/chunks/{inspect-BQELJ5EI.js → inspect-4DASZGPR.js} +1 -1
- package/dist/chunks/{inspect-HJQWRFHR.js → inspect-FVB5P54P.js} +1 -1
- package/dist/chunks/{inspect-SEGNEPGI.js → inspect-GKZFZINR.js} +1 -1
- package/dist/chunks/{inspect-DWOQ6566.js → inspect-IU2VMHWZ.js} +1 -1
- package/dist/chunks/{list-S2XKQMNX.js → list-5LMFTD7U.js} +1 -1
- package/dist/chunks/{list-HS54LLJ5.js → list-OYT6T3TA.js} +1 -1
- package/dist/chunks/{list-OCU47YHP.js → list-TL7VBVR5.js} +1 -1
- package/dist/chunks/{login-SKAMFH7S.js → login-PFAKA6JO.js} +1 -1
- package/dist/chunks/{login-K6VYVJPS.js → login-UWL7N6ZS.js} +1 -1
- package/dist/chunks/{logs-KZSKOQUN.js → logs-4FOJKWAW.js} +1 -1
- package/dist/chunks/{ls-ZYM3DQXI.js → ls-6TRT3UFZ.js} +1 -1
- package/dist/chunks/{ls-LBBI45ZT.js → ls-B3D7XA2S.js} +1 -1
- package/dist/chunks/{ls-G5NTVYUB.js → ls-H7YO6MS5.js} +1 -1
- package/dist/chunks/{ls-NUM6IQL6.js → ls-SJDE4U7I.js} +1 -1
- package/dist/chunks/{ls-TE7BAMHR.js → ls-SXE2THDP.js} +1 -1
- package/dist/chunks/{ls-DTEGGHQA.js → ls-VFV23YCF.js} +1 -1
- package/dist/chunks/{ls-LCY7BHOP.js → ls-VNOGQ64O.js} +1 -1
- package/dist/chunks/{mutate-BAFVNNRU.js → mutate-IGC37SCR.js} +1 -1
- package/dist/chunks/{notifications-3EB3ZEU3.js → notifications-47EDEA5C.js} +1 -1
- package/dist/chunks/{open-J4X5KJ6A.js → open-NP444BUR.js} +1 -1
- package/dist/chunks/{openapi-C5BHMHWS.js → openapi-LW24FRTC.js} +1 -1
- package/dist/chunks/{permissions-2WMWMXFP.js → permissions-CP57O3II.js} +1 -1
- package/dist/chunks/{prompt-missing-credentials-VS3ZJSCQ.js → prompt-missing-credentials-C3OIQONK.js} +1 -1
- package/dist/chunks/{publish-WWI5HOAL.js → publish-5TK3IVYM.js} +1 -1
- package/dist/chunks/{pull-MTQAMT4L.js → pull-FCQKXYBD.js} +1 -1
- package/dist/chunks/{purchase-domain-if-available-ZIIAF7CC.js → purchase-domain-if-available-QBDRKJZ5.js} +1 -1
- package/dist/chunks/{push-PBKUSKXQ.js → push-SIR5XTJN.js} +1 -1
- package/dist/chunks/{query-5VGUVE2A.js → query-IEBWCCMJ.js} +1 -1
- package/dist/chunks/{reauthenticate-UGBXSWZE.js → reauthenticate-XSNRCXPC.js} +1 -1
- package/dist/chunks/{reorder-S2ZJML5K.js → reorder-TPLZXSRB.js} +1 -1
- package/dist/chunks/{reply-3GFULOMZ.js → reply-BCDQQ6I2.js} +1 -1
- package/dist/chunks/{resolve-USEBSFUT.js → resolve-VKJAE7KO.js} +1 -1
- package/dist/chunks/{restore-JD7IGDTY.js → restore-TZAXCNLL.js} +1 -1
- package/dist/chunks/{rm-LL2AWOZT.js → rm-53HZ5XOQ.js} +1 -1
- package/dist/chunks/{rm-RHRKS7XG.js → rm-A2NTZ4EJ.js} +1 -1
- package/dist/chunks/{rm-BYOBKSWY.js → rm-DPVWWH4Q.js} +1 -1
- package/dist/chunks/{rm-EQYVIFNX.js → rm-TTZBAVUG.js} +1 -1
- package/dist/chunks/{rm-3V47KPK6.js → rm-V4M46PRZ.js} +1 -1
- package/dist/chunks/{routes-NID5V7EJ.js → routes-PKCKZ5T6.js} +1 -1
- package/dist/chunks/{rule-inspect-5DZ7OXGE.js → rule-inspect-5QXLEJZA.js} +1 -1
- package/dist/chunks/{rules-CM2ARIWZ.js → rules-2SBYOL6R.js} +1 -1
- package/dist/chunks/{schema-V75RRXXF.js → schema-OGGOD3HX.js} +1 -1
- package/dist/chunks/{schema-SZUKDSY2.js → schema-PGGJZ2AT.js} +1 -1
- package/dist/chunks/{select-org-SH4JT6RI.js → select-org-VBP5DCYP.js} +1 -1
- package/dist/chunks/{set-LY4YI5FZ.js → set-6BCSH3I3.js} +1 -1
- package/dist/chunks/{setup-and-link-MWLALWAS.js → setup-and-link-FPGTZUH6.js} +1 -1
- package/dist/chunks/{tags-P5GB7HTF.js → tags-77REB4BF.js} +1 -1
- package/dist/chunks/{types-OC7OTQNK.js → types-4C5N66YA.js} +1 -1
- package/dist/chunks/{update-SOD622HT.js → update-7BNVIJWB.js} +1 -1
- package/dist/commands/build/index.js +1 -1
- package/dist/commands/deploy/index.js +4 -4
- package/dist/commands/dev/index.js +2 -2
- package/dist/commands/env/index.js +1 -1
- package/dist/commands/link/index.js +1 -1
- package/dist/commands/list/index.js +1 -1
- package/dist/commands-bulk.js +48 -36
- package/dist/index.js +2 -2
- package/dist/internal-build.js +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +14 -14
- package/dist/chunks/chunk-5RR3435W.js +0 -10
- package/dist/chunks/chunk-U5C6XOLA.js +0 -9
- package/dist/chunks/chunk-W6LNIG5O.js +0 -7
|
@@ -4,7 +4,7 @@ import { dirname as __dirname_ } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
const __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{fetchDeploymentBuildEnv,resolvePerDirectoryLinkRoot}from"../../chunks/chunk-
|
|
7
|
+
import{fetchDeploymentBuildEnv,resolvePerDirectoryLinkRoot}from"../../chunks/chunk-T3PAZMDW.js";import{isIgnoredFile,singleFileConfig,singleFileProjectSettings,validatePaths,validateRootDirectory}from"../../chunks/chunk-6TEFVB2U.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-Y35RMGOU.js";import"../../chunks/chunk-MZ6DNAVL.js";import{DeployTelemetryClient,Now,UploadErrorMissingArchive,getBuildMachineResourceConfig,getProductionUrl,printDeploymentStatus,printPrebuiltFilePathMapIgnoreWarning}from"../../chunks/chunk-ZQBMRI57.js";import{require_async_sema}from"../../chunks/chunk-NZ2TFADV.js";import"../../chunks/chunk-X5GP2FBT.js";import"../../chunks/chunk-V6Y6UK6B.js";import{parseRepoUrl}from"../../chunks/chunk-SYEKOJHT.js";import"../../chunks/chunk-EAUDC24V.js";import{pickOverrides}from"../../chunks/chunk-FU7KGU6V.js";import{require_dist as require_dist2,require_ignore}from"../../chunks/chunk-YAPHSZJ7.js";import"../../chunks/chunk-WJ4VNTE3.js";import{compileVercelConfig}from"../../chunks/chunk-SZRSBECO.js";import"../../chunks/chunk-RRDNKB2X.js";import"../../chunks/chunk-MVGTMPMI.js";import"../../chunks/chunk-SACGQMVQ.js";import"../../chunks/chunk-U56NHYAH.js";import{require_ci_info}from"../../chunks/chunk-2EYYB6YN.js";import{require_semver}from"../../chunks/chunk-BPUANOGW.js";import"../../chunks/chunk-3E364MJE.js";import"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-JORUFFOD.js";import"../../chunks/chunk-O4FDRZ22.js";import"../../chunks/chunk-T3GQAMBJ.js";import"../../chunks/chunk-P2O5DOYE.js";import{isGuidanceEnabled}from"../../chunks/chunk-A5R2HHNK.js";import{stamp_default}from"../../chunks/chunk-A2RZZQEP.js";import{getSubcommand}from"../../chunks/chunk-ETV3C2CV.js";import"../../chunks/chunk-J24BABG4.js";import{ensureLink,parseEnv}from"../../chunks/chunk-7SGM233C.js";import"../../chunks/chunk-3YQVBYQD.js";import"../../chunks/chunk-I7FGFRN3.js";import"../../chunks/chunk-PVASGBEF.js";import"../../chunks/chunk-MVCAUS4F.js";import{continueSubcommand,deployCommand,deprecatedArchiveSplitTgz,describeSubcommand,getCommandAliases,initSubcommand}from"../../chunks/chunk-OB5XGIDM.js";import"../../chunks/chunk-OH2RT2GN.js";import"../../chunks/chunk-UFXKCETS.js";import"../../chunks/chunk-RZGWCQP7.js";import"../../chunks/chunk-AG5QQNJ3.js";import"../../chunks/chunk-AU42HSQ3.js";import"../../chunks/chunk-L5FUUGYX.js";import"../../chunks/chunk-QC47UKDR.js";import"../../chunks/chunk-QJKJBD2M.js";import"../../chunks/chunk-MYCQIZU6.js";import"../../chunks/chunk-CNU4T7FO.js";import"../../chunks/chunk-LU5O3NH7.js";import"../../chunks/chunk-AMDHTZDV.js";import"../../chunks/chunk-2JBVMF2Y.js";import"../../chunks/chunk-JLXG2XWW.js";import"../../chunks/chunk-B4YYOSPY.js";import"../../chunks/chunk-I3D36ZLJ.js";import"../../chunks/chunk-S7XZC23O.js";import"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-6LXX5P3A.js";import"../../chunks/chunk-MSH7V3FL.js";import"../../chunks/chunk-SCV7XEEO.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import{parseMeta}from"../../chunks/chunk-CZSOZKHX.js";import"../../chunks/chunk-Q7D7RGXM.js";import{parseTarget}from"../../chunks/chunk-XEQT373M.js";import{getDeployment}from"../../chunks/chunk-J2LAZELI.js";import{mapCertError}from"../../chunks/chunk-E6UKNYFF.js";import"../../chunks/chunk-GRTIWUV2.js";import{help}from"../../chunks/chunk-5O2CW3SX.js";import{table}from"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-T6GXMIXO.js";import{AGENT_REASON,AGENT_STATUS,buildCommandWithYes,outputAgentError,withGlobalFlags}from"../../chunks/chunk-5YQP44VL.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{validateJsonOutput,wantsMachineReadableOutput}from"../../chunks/chunk-D4MW3RDW.js";import{highlight,readLocalConfig}from"../../chunks/chunk-HWYHRPWP.js";import"../../chunks/chunk-HMS3UIQ2.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{TelemetryClient}from"../../chunks/chunk-TNZMCRAP.js";import"../../chunks/chunk-VKXEOL4K.js";import"../../chunks/chunk-YYPNUQDI.js";import"../../chunks/chunk-4SAVH3H7.js";import{require_types}from"../../chunks/chunk-ZS2WS4AM.js";import"../../chunks/chunk-AOWWC6WZ.js";import{getFetchDispatcher}from"../../chunks/chunk-MY4MONOH.js";import{isArgumentError,parseArguments}from"../../chunks/chunk-R4VVQRLX.js";import{quoteArg}from"../../chunks/chunk-BKV35LVB.js";import{getFlagsSpecification}from"../../chunks/chunk-5IPBCD7K.js";import{VERCEL_DIR,VERCEL_DIR_PROJECT,addToGitIgnore,createGitMeta,findProjectsFromPath,getGitConfigPath,getGitExecutable,getLinkFromDir,getProjectLink,getRepoLink,getVercelDirectory,isOwnerLookupUnavailableLink,isRemoteLookupSkippedLink,linkFolderToProject,parseGitConfig,pluckRemoteUrls,require_lib}from"../../chunks/chunk-SWJYZETA.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import{printAlignedLabel}from"../../chunks/chunk-N7Q2IESO.js";import"../../chunks/chunk-WPQN5UKR.js";import"../../chunks/chunk-VOZEB6PD.js";import{AliasDomainConfigured,BuildError,BuildsRateLimited,ConflictingConfigFiles,ConflictingFilePath,ConflictingPathSegment,DeploymentNotFound,DeploymentsRateLimited,DeprecatedNowJson,DomainNotFound,DomainNotVerified,DomainPermissionDenied,DomainVerificationFailed,InvalidDomain,InvalidToken,MissingBuildScript,NotDomainOwner,NowError,SchemaValidationFailed,TooManyRequests,UserAborted,code,isAPIError,require_bytes}from"../../chunks/chunk-YIIPBH2D.js";import{getCommandName,packageName}from"../../chunks/chunk-JESNVRVR.js";import{cliErrorFromUnknown,emoji,link_default,output_manager_default,prependEmoji,recordCliError,require_build_utils}from"../../chunks/chunk-75IAMKGV.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__toESM}from"../../chunks/chunk-BZENIQ7N.js";var import_build_utils9=__toESM(require_build_utils(),1),import_client=__toESM(require_dist2(),1),import_error_utils2=__toESM(require_dist(),1);var import_bytes=__toESM(require_bytes(),1),import_chalk=__toESM(require_source(),1),import_fs_extra4=__toESM(require_lib(),1),import_ms=__toESM(require_ms(),1);import{tmpdir}from"os";import{basename as basename3,dirname as dirname2,extname,join as join13,resolve as resolve3}from"path";async function createDeploy(client,now,contextName,path2,createArgs,org,isSettingUpProject,archive){try{return await now.create(path2,createArgs,org,isSettingUpProject,archive)}catch(err){if(isAPIError(err)){if(err.code==="rate_limited")throw new DeploymentsRateLimited(err.message);if(err.code==="domain_missing")throw new DomainNotFound(err.value);if(err.code==="domain_not_found"&&err.domain)throw new DomainNotFound(err.domain);if(err.code==="domain_not_verified"&&err.domain)throw new DomainNotVerified(err.domain);if(err.code==="domain_not_verified"&&err.value)throw new DomainVerificationFailed(err.value);if(err.code==="not_domain_owner")throw new NotDomainOwner(err.message);if(err.code==="builds_rate_limited")throw new BuildsRateLimited(err.message,{ctaLabel:err.ctaLabel,ctaUrl:err.ctaUrl,action:err.action,link:err.link});if(err.code==="forbidden")throw new DomainPermissionDenied(err.value,contextName);if(err.code==="bad_request"&&err.keyword)throw new SchemaValidationFailed(err.message,err.keyword,err.dataPath,err.params);if(err.code==="domain_configured")throw new AliasDomainConfigured(err);if(err.code==="missing_build_script")throw new MissingBuildScript(err);if(err.code==="conflicting_file_path")throw new ConflictingFilePath(err);if(err.code==="conflicting_path_segment")throw new ConflictingPathSegment(err);if(err.code==="cert_missing"){let{default:generateCertForDeploy}=await import("../../chunks/generate-cert-for-deploy-UNRGDROB.js"),result=await generateCertForDeploy(client,contextName,err.value);return result instanceof NowError?result:createDeploy(client,now,contextName,path2,createArgs,org,isSettingUpProject)}if(err.code==="not_found")throw new DeploymentNotFound({context:contextName});let certError=mapCertError(err);if(certError)return certError}throw err}}async function getDeploymentChecks(client,deploymentId){return await client.fetch(`/v1/deployments/${encodeURIComponent(deploymentId)}/checks`)}async function getDeploymentCheckRuns(client,deploymentId){return await client.fetch(`/v2/deployments/${encodeURIComponent(deploymentId)}/check-runs`)}function parseNdjson(text){let entries=[];for(let line of text.split(`
|
|
8
8
|
`))if(line.trim())try{entries.push(JSON.parse(line))}catch{}return entries}async function getDeploymentCheckRunLogs(client,deploymentId,checkRunId){let url=`/v2/deployments/${encodeURIComponent(deploymentId)}/check-runs/${encodeURIComponent(checkRunId)}/logs`;await new Promise(resolve4=>setTimeout(resolve4,1e3));for(let attempt=0;attempt<5;attempt++){attempt>0&&await new Promise(resolve4=>setTimeout(resolve4,2e3));let res=await client.fetch(url,{json:!1}),text=typeof res=="string"?res:await res.text(),entries=parseNdjson(text);if(entries.some(e=>e.level==="eof"))return entries.filter(e=>e.level!=="eof"&&e.level!=="debug").map(({level,timestamp,message})=>({level,timestamp,message}))}return[]}var import_fs_extra=__toESM(require_lib(),1);import{join}from"path";async function getPrebuiltJson(directory){try{return await import_fs_extra.default.readJSON(join(directory,"builds.json"))}catch{}return null}var PROTECTION_METHODS=[{setting:"ssoProtection",id:"vercel_authentication",name:"Vercel Authentication"},{setting:"passwordProtection",id:"password",name:"Password Protection"}];async function getEnabledProtection(client,project){try{let settings=await client.fetch(`/v9/projects/${encodeURIComponent(project.id)}`,{accountId:project.accountId});return PROTECTION_METHODS.filter(method=>settings[method.setting])}catch(err){return output_manager_default.debug(`Could not read Deployment Protection settings: ${err}`),null}}import{resolve}from"path";var SUPPORTED_PROVIDERS=new Set(["github","gitlab","bitbucket"]),defaultDeps={getGitConfigPath,parseGitConfig,fetchProject:(client,project)=>client.fetch(`/v9/projects/${encodeURIComponent(project.id)}`,{accountId:project.accountId}),buildCommand:(client,command)=>withGlobalFlags(client,command,{preserveProject:!0})};async function getGitConnectRecommendation(client,cwd,project,options={}){let{alreadyOffered=!1,deps=defaultDeps}=options;try{if(project.link||alreadyOffered)return;let gitConfigPath=deps.getGitConfigPath({cwd});if(!gitConfigPath)return;let gitConfig=await deps.parseGitConfig(gitConfigPath),remoteUrls=gitConfig&&pluckRemoteUrls(gitConfig);if(!remoteUrls)return;let remotes=Object.values(remoteUrls);if(!remotes.some(remoteUrl=>{let repo=parseRepoUrl(remoteUrl);return repo&&SUPPORTED_PROVIDERS.has(repo.provider)})||client.nonInteractive&&remotes.length!==1||(await deps.fetchProject(client,project)).link)return;let cwdFlag=resolve(cwd)===resolve(client.cwd)?"":` --cwd ${quoteArg(cwd)}`;return deps.buildCommand(client,`git connect${cwdFlag}`)}catch(error){output_manager_default.debug(`Failed to resolve Git connection guidance: ${error}`);return}}var import_types=__toESM(require_types(),1),validArchiveFormats=new Set(import_types.VALID_ARCHIVE_FORMATS);function isValidArchive(archive){return validArchiveFormats.has(archive)}function getErrorCta(source){if(typeof source.ctaLabel=="string"&&typeof source.ctaUrl=="string")return{label:source.ctaLabel,url:source.ctaUrl};if(typeof source.action=="string"&&typeof source.link=="string")return{label:source.action,url:source.link}}var DescribeError=class extends Error{constructor(reason,message){super(message);this.reason=reason}};var DescribeTelemetryClient=class extends TelemetryClient{trackCliOptionId(value){value&&this.trackCliOption({option:"id",value:this.redactedValue})}trackCliOptionAwsAccountId(value){value&&this.trackCliOption({option:"aws-account-id",value:this.redactedValue})}trackCliFlagJson(value){value&&this.trackCliFlag("json")}};import{createHash as createHash3}from"node:crypto";import{createHash as createHash2}from"node:crypto";function getFunctionConfig(lambda){return{runtime:lambda.runtime,handler:lambda.handler,architecture:lambda.architecture,environment:Object.fromEntries(Object.entries(lambda.environment).filter(entry=>typeof entry[1]=="string")),..."launcherType"in lambda&&lambda.launcherType==="Nodejs"?{launcherType:lambda.launcherType,awsLambdaHandler:lambda.awsLambdaHandler,shouldAddHelpers:lambda.shouldAddHelpers,shouldAddSourcemapSupport:lambda.shouldAddSourcemapSupport,shouldDisableAutomaticFetchInstrumentation:lambda.shouldDisableAutomaticFetchInstrumentation,useWebApi:lambda.useWebApi}:{},memory:lambda.memory,affinity:lambda.affinity,maxConcurrency:lambda.maxConcurrency,maxDuration:lambda.maxDuration,regions:lambda.regions,functionFailoverRegions:lambda.functionFailoverRegions,supportsResponseStreaming:lambda.supportsResponseStreaming,framework:lambda.framework&&{...lambda.framework}}}var import_build_utils=__toESM(require_build_utils(),1),ROOT_BOOTSTRAP_PATH="bootstrap",USER_BOOTSTRAP_PATH="___vc_bootstrap",NATIVELY_WRAPPER_SUPPORTED_FAMILIES=["nodejs","python","ruby","java","dotnetcore","bun","executable"],BOOTSTRAP_SHIM=`#!/bin/sh
|
|
9
9
|
USER_BOOTSTRAP="/var/task/${USER_BOOTSTRAP_PATH}"
|
|
10
10
|
|
|
@@ -20,7 +20,7 @@ exec "$USER_BOOTSTRAP" "$@"
|
|
|
20
20
|
`):output_manager_default.error(message),code2),parsed;try{parsed=parseArguments(client.argv.slice(2),getFlagsSpecification(describeSubcommand.options))}catch(error){return fail("invalid_arguments",`${isArgumentError(error)?error.message:"Invalid describe options"}. Run \`vercel deploy describe --help\` for usage.`,2)}asJson=parsed.flags["--json"]===!0;let deploymentId=parsed.flags["--id"],awsAccountId=parsed.flags["--aws-account-id"];if((parsed.args[0]==="deploy"?parsed.args.slice(1):parsed.args).length>1)return fail("invalid_arguments","Unexpected positional arguments. Run `vercel deploy describe --help` for usage.",2);if(!deploymentId||!/^dpl_[a-zA-Z0-9]+$/.test(deploymentId))return fail("invalid_arguments","Provide a deployment ID with --id, such as --id dpl_xxx.",2);if(!awsAccountId||!/^\d{12}$/.test(awsAccountId))return fail("invalid_arguments","Provide a 12-digit AWS account ID with --aws-account-id.",2);if(process.platform==="win32")return fail("unsupported_platform","vercel deploy describe is not supported on Windows yet. Run it on macOS or Linux.");let telemetry=new DescribeTelemetryClient({opts:{store:client.telemetryEventStore}});telemetry.trackCliOptionId(deploymentId),telemetry.trackCliOptionAwsAccountId(awsAccountId),telemetry.trackCliFlagJson(parsed.flags["--json"]);try{let project=await resolveDescribeProject(client),explicitTeam=parsed.flags["--scope"]?client.config.currentTeam:process.env.VERCEL_ORG_ID;if(explicitTeam&&explicitTeam!==project.orgId)return fail("scope_mismatch","The selected team does not match the local project link. Use the linked team, or run `vercel pull --yes` with the intended VERCEL_ORG_ID and VERCEL_PROJECT_ID.");if(process.env.VERCEL_PROJECT_ID&&process.env.VERCEL_PROJECT_ID!==project.projectId)return fail("project_mismatch","VERCEL_PROJECT_ID differs from the linked project. Run `vercel pull --yes` to restore settings for the intended project.");client.config.currentTeam=project.orgId.startsWith("team_")?project.orgId:void 0,asJson||output_manager_default.log(`Preparing ${deploymentId} in team ${project.orgId} for AWS account ${awsAccountId}`);let directory=await describeDeployment(client,{directory:project.directory,repoRootPath:project.repoRootPath,deploymentId,awsAccountId,teamId:project.orgId,quiet:asJson}),descriptor=join10(directory,"descriptor.json");if(asJson)client.stdout.write(`${JSON.stringify({deployment:{id:deploymentId},awsAccountId,directory,descriptor})}
|
|
21
21
|
`);else{client.stdout.write(`${descriptor}
|
|
22
22
|
`),output_manager_default.log(`Prepared function packages in ${directory}`);let cwd=project.directory===client.cwd?"":` --cwd ${quoteArg(project.directory)}`;output_manager_default.log(`Provision the functions in descriptor.json, then run:
|
|
23
|
-
vercel deploy continue --id ${deploymentId}${cwd}`)}return 0}catch(error){return output_manager_default.debug(error instanceof Error?error.stack??error.message:String(error)),error instanceof DescribeError?fail(error.reason,error.message):error instanceof InvalidToken||isAPIError(error)&&error.status===401?fail("not_authorized","Could not authenticate with Vercel. Check VERCEL_TOKEN in CI, or run `vercel login`."):isAPIError(error)&&error.status===403?fail("not_authorized","Vercel denied access to this deployment. Check that your token has access to the linked project and team."):isAPIError(error)&&error.status===404?fail("not_found",`Deployment ${deploymentId} was not found, or manual provisioning is not enabled for this team.`):isAPIError(error)&&error.status<500&&error.serverMessage?fail("api_error",error.serverMessage):fail("describe_failed","Could not prepare deployment functions. Check the local build and deployment access, then rerun this command.")}}var import_fs_extra3=__toESM(require_lib(),1);import{join as join12}from"path";var import_fs_extra2=__toESM(require_lib(),1),import_ci_info=__toESM(require_ci_info(),1),import_build_utils8=__toESM(require_build_utils(),1),import_error_utils=__toESM(require_dist(),1);import{join as join11}from"path";var VERCEL_DIR_ANONYMOUS="anonymous.json";function anonymousStatePath(cwd){return join11(cwd,VERCEL_DIR,VERCEL_DIR_ANONYMOUS)}async function readAnonymousState(cwd){try{let state=await(0,import_fs_extra2.readJSON)(anonymousStatePath(cwd));if(typeof state?.projectId=="string"&&typeof state.token=="string"&&typeof state.claimUrl=="string"&&typeof state.expiresAt=="number")return state}catch{}return null}async function writeAnonymousState(cwd,state){let path2=anonymousStatePath(cwd);await(0,import_fs_extra2.outputJSON)(path2,state,{spaces:2,mode:384}),await(0,import_fs_extra2.chmod)(path2,384),await addToGitIgnore(cwd)}async function clearAnonymousState(cwd){await(0,import_fs_extra2.remove)(anonymousStatePath(cwd))}async function bootstrapAnonymousProject(client){let{projectId,token,claimUrl,expiresAt}=await client.fetch("/v1/anonymous/projects?surface=cli",{method:"POST",body:{},useCurrentTeam:!1,retry:{retries:0}});return{projectId,token,claimUrl,expiresAt}}async function ensureAnonymousLink(client,cwd,{requireExistingState=!1,confirmed=!0}={}){if(import_ci_info.default.isCI||!!((0,import_build_utils8.getPlatformEnv)("ORG_ID")&&(0,import_build_utils8.getPlatformEnv)("PROJECT_ID"))||!!await getLinkFromDir(getVercelDirectory(cwd))||!!(await getRepoLink(client,cwd))?.repoConfig)return"refused";let state=await readAnonymousState(cwd);if(state&&state.expiresAt<=Date.now())return output_manager_default.prettyError({message:`Your temporary deployment has expired. Run ${getCommandName("login")} to create an account and keep deploying this app.`}),"failed";if(!state&&requireExistingState)return"refused";if(!confirmed&&!state)return"confirmation-required";if(!state){try{state=await bootstrapAnonymousProject(client)}catch(err){return output_manager_default.debug(`Anonymous bootstrap failed: ${(0,import_error_utils.errorToString)(err)}`),"refused"}await writeAnonymousState(cwd,state),output_manager_default.log("Not authenticated. Deploying anonymously.")}return client.authConfig={token:state.token,skipWrite:!0},delete process.env.VERCEL_TEAM_ID,{status:"linked",anonymous:!0,expiresAt:state.expiresAt,claimUrl:state.claimUrl,org:{type:"user",id:"",slug:"anonymous"},project:{id:state.projectId,name:state.projectId}}}function validateAnonymousTarget(isAnonymous,target){return isAnonymous&&target&&target!=="production"?(output_manager_default.error(`Anonymous deployments always target production, so "${target}" is not available. Remove the ${param("--target")} option, or run ${getCommandName("login")} to deploy to other environments.`),!1):!0}async function setupAnonymousDeployment(client,cwd,{isAnonymous,dryRun}){isAnonymous||await clearAnonymousState(cwd);let anonymousLink;if(isAnonymous){let anonymous=await ensureAnonymousLink(client,cwd,{requireExistingState:dryRun});if(anonymous==="refused"){output_manager_default.log("Temporary deployments aren't available for this attempt. Log in to continue.");let{default:promptMissingCredentials}=await import("../../chunks/prompt-missing-credentials-VS3ZJSCQ.js"),loginExitCode=await promptMissingCredentials(client);if(loginExitCode!==0)return loginExitCode;isAnonymous=!1}else{if(anonymous==="failed")return 1;if(anonymous==="confirmation-required")return 1;anonymousLink=anonymous}}return{isAnonymous,anonymousLink}}async function handleAnonymousDeploymentError({client,cwd,error,link,isV0,retry}){if(!(!link||!isAPIError(error))){if(error.code==="anonymous_project_claimed"){if(client.nonInteractive||!client.stdin.isTTY)return output_manager_default.prettyError({message:`This project was claimed successfully. Run ${getCommandName("login")} to continue deploying it.`}),1;output_manager_default.log("This project was claimed successfully. Log in to continue deploying it.");let loginExitCode;try{let{default:login}=await import("../../chunks/login-SKAMFH7S.js");loginExitCode=await login(client,{shouldParseArgs:!1})}catch(loginError){return printError(loginError),1}if(loginExitCode!==0)return loginExitCode;let claimedProjectLink=await ensureLink("deploy",client,cwd,{autoConfirm:!0,projectName:link.project.id,failIfNotFound:!0,allowOwnerLookupFallback:!0,v0:isV0});return typeof claimedProjectLink=="number"?claimedProjectLink:(await linkFolderToProject(client,cwd,{projectId:claimedProjectLink.project.id,orgId:claimedProjectLink.org.id},claimedProjectLink.project.name,claimedProjectLink.org.slug,"link",!0,!1),await clearAnonymousState(cwd),retry())}if(error.status===401||error.status===410)return await clearAnonymousState(cwd),output_manager_default.prettyError({message:`Your temporary deployment has expired. Run ${getCommandName("login")} to create an account and keep deploying this app.`}),1}}async function runImplicitBuild(client,cwd){let projectJsonPath=join12(cwd,VERCEL_DIR,VERCEL_DIR_PROJECT),projectJsonExists=await import_fs_extra3.default.pathExists(projectJsonPath);projectJsonExists||await import_fs_extra3.default.outputJSON(projectJsonPath,{settings:{}},{spaces:2}),await import_fs_extra3.default.pathExists(join12(cwd,"package.json"))&&output_manager_default.log("Building your project locally\u2026");let originalArgv=client.argv,originalCwd=client.cwd,originalStdout=client.stdout,previousVercelFirstDeployment=process.env.VERCEL_FIRST_DEPLOYMENT;client.cwd=cwd,client.setArgv([...originalArgv.slice(0,2),"build","--prod","--yes"]),process.env.VERCEL_FIRST_DEPLOYMENT="1",client.stdout=createSinkStream();try{let build=(await import("../build/index.js")).default;return await build(client)}finally{client.setArgv(originalArgv),client.cwd=originalCwd,client.stdout=originalStdout,previousVercelFirstDeployment===void 0?delete process.env.VERCEL_FIRST_DEPLOYMENT:process.env.VERCEL_FIRST_DEPLOYMENT=previousVercelFirstDeployment,projectJsonExists||await import_fs_extra3.default.remove(projectJsonPath)}}function createSinkStream(){return{isTTY:!1,write:()=>!0}}var COMMAND_CONFIG={init:getCommandAliases(initSubcommand),continue:getCommandAliases(continueSubcommand),describe:getCommandAliases(describeSubcommand)},deploy_default=async client=>{let telemetryClient=new DeployTelemetryClient({opts:{store:client.telemetryEventStore}}),parsedArguments=null,flagsSpecification=getFlagsSpecification(deployCommand.options);try{parsedArguments=parseArguments(client.argv.slice(2),flagsSpecification,{permissive:!0})}catch(error){return printError(error),2}let subArgs=parsedArguments.args[0]===deployCommand.name?parsedArguments.args.slice(1):parsedArguments.args,{subcommand,subcommandOriginal}=getSubcommand(subArgs,COMMAND_CONFIG);function printSubcommandHelp(command){output_manager_default.print(help(command,{parent:deployCommand,columns:client.stderr.columns}))}switch(subcommand){case"init":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(initSubcommand),0):(telemetryClient.trackCliSubcommandInit(subcommandOriginal),handleInitDeployment(client,telemetryClient));case"continue":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(continueSubcommand),0):(telemetryClient.trackCliSubcommandContinue(subcommandOriginal),handleContinueSubcommand(client,telemetryClient));case"describe":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(describeSubcommand),0):(telemetryClient.trackCliSubcommandDescribe(subcommandOriginal),describe(client));default:return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy"),output_manager_default.print(help(deployCommand,{columns:client.stderr.columns})),0):handleDefaultDeploy(client,telemetryClient)}};async function handleInitDeployment(client,telemetryClient){let flagsSpecification=getFlagsSpecification(initSubcommand.options),parsedArguments;try{parsedArguments=parseArguments(client.argv.slice(2),flagsSpecification)}catch(error2){return printError(error2),2}telemetryClient.trackCliFlagJson(parsedArguments.flags["--json"]),telemetryClient.trackCliOptionFormat(parsedArguments.flags["--format"]),telemetryClient.trackCliOptionProject(parsedArguments.flags["--project"]);let projectNameOrId=parsedArguments.flags["--project"],formatResult=validateJsonOutput(parsedArguments.flags);if(!formatResult.valid)return output_manager_default.error(formatResult.error),2;let asJson=formatResult.jsonOutput||client.nonInteractive,args=parsedArguments.args;args[0]==="deploy"&&(args=args.slice(1)),args[0]==="init"&&(args=args.slice(1));let paths;args.length>0?(paths=args.map(item=>resolve3(client.cwd,item)),telemetryClient.trackCliArgumentProjectPath(paths[0])):paths=[client.cwd];let pathValidation=await validatePaths(client,paths);if(!pathValidation.valid)return pathValidation.exitCode;await compileVercelConfig(paths[0]);let localConfig=paths[0]===client.cwd?client.localConfig||readLocalConfig(paths[0]):readLocalConfig(paths[0]);if(localConfig){client.localConfig=localConfig;let{version}=localConfig,file=highlight(localConfig[import_client.fileNameSymbol]),prop=code("version");if(version)if(typeof version=="number"){if(version!==2){let two=code(String(2));return output_manager_default.error(`The value of the ${prop} property within ${file} can only be ${two}.`),1}}else return output_manager_default.error(`The ${prop} property inside your ${file} file must be a number.`),1}let{log,debug,error}=output_manager_default,quiet=!client.stdout.isTTY,{path:cwd}=pathValidation,autoConfirm=parsedArguments.flags["--yes"],target=parseTarget({flagName:"target",flags:parsedArguments.flags});telemetryClient.trackTargetEnvironment(target);let parsedArchive=parsedArguments.flags["--archive"];if(typeof parsedArchive=="string"&&!(isValidArchive(parsedArchive)||parsedArchive===deprecatedArchiveSplitTgz))return output_manager_default.error(`Format must be one of: ${import_client.VALID_ARCHIVE_FORMATS.join(", ")}`),2;parsedArchive===deprecatedArchiveSplitTgz&&output_manager_default.print(`${prependEmoji(`${param("--archive=tgz")} now has the same behavior as ${param("--archive=split-tgz")}. Please use ${param("--archive=tgz")} instead.`,emoji("warning"))}
|
|
23
|
+
vercel deploy continue --id ${deploymentId}${cwd}`)}return 0}catch(error){return output_manager_default.debug(error instanceof Error?error.stack??error.message:String(error)),error instanceof DescribeError?fail(error.reason,error.message):error instanceof InvalidToken||isAPIError(error)&&error.status===401?fail("not_authorized","Could not authenticate with Vercel. Check VERCEL_TOKEN in CI, or run `vercel login`."):isAPIError(error)&&error.status===403?fail("not_authorized","Vercel denied access to this deployment. Check that your token has access to the linked project and team."):isAPIError(error)&&error.status===404?fail("not_found",`Deployment ${deploymentId} was not found, or manual provisioning is not enabled for this team.`):isAPIError(error)&&error.status<500&&error.serverMessage?fail("api_error",error.serverMessage):fail("describe_failed","Could not prepare deployment functions. Check the local build and deployment access, then rerun this command.")}}var import_fs_extra3=__toESM(require_lib(),1);import{join as join12}from"path";var import_fs_extra2=__toESM(require_lib(),1),import_ci_info=__toESM(require_ci_info(),1),import_build_utils8=__toESM(require_build_utils(),1),import_error_utils=__toESM(require_dist(),1);import{join as join11}from"path";var VERCEL_DIR_ANONYMOUS="anonymous.json";function anonymousStatePath(cwd){return join11(cwd,VERCEL_DIR,VERCEL_DIR_ANONYMOUS)}async function readAnonymousState(cwd){try{let state=await(0,import_fs_extra2.readJSON)(anonymousStatePath(cwd));if(typeof state?.projectId=="string"&&typeof state.token=="string"&&typeof state.claimUrl=="string"&&typeof state.expiresAt=="number")return state}catch{}return null}async function writeAnonymousState(cwd,state){let path2=anonymousStatePath(cwd);await(0,import_fs_extra2.outputJSON)(path2,state,{spaces:2,mode:384}),await(0,import_fs_extra2.chmod)(path2,384),await addToGitIgnore(cwd)}async function clearAnonymousState(cwd){await(0,import_fs_extra2.remove)(anonymousStatePath(cwd))}async function bootstrapAnonymousProject(client){let{projectId,token,claimUrl,expiresAt}=await client.fetch("/v1/anonymous/projects?surface=cli",{method:"POST",body:{},useCurrentTeam:!1,retry:{retries:0}});return{projectId,token,claimUrl,expiresAt}}async function ensureAnonymousLink(client,cwd,{requireExistingState=!1,confirmed=!0}={}){if(import_ci_info.default.isCI||!!((0,import_build_utils8.getPlatformEnv)("ORG_ID")&&(0,import_build_utils8.getPlatformEnv)("PROJECT_ID"))||!!await getLinkFromDir(getVercelDirectory(cwd))||!!(await getRepoLink(client,cwd))?.repoConfig)return"refused";let state=await readAnonymousState(cwd);if(state&&state.expiresAt<=Date.now())return output_manager_default.prettyError({message:`Your temporary deployment has expired. Run ${getCommandName("login")} to create an account and keep deploying this app.`}),"failed";if(!state&&requireExistingState)return"refused";if(!confirmed&&!state)return"confirmation-required";if(!state){try{state=await bootstrapAnonymousProject(client)}catch(err){return output_manager_default.debug(`Anonymous bootstrap failed: ${(0,import_error_utils.errorToString)(err)}`),"refused"}await writeAnonymousState(cwd,state),output_manager_default.log("Not authenticated. Deploying anonymously.")}return client.authConfig={token:state.token,skipWrite:!0},delete process.env.VERCEL_TEAM_ID,{status:"linked",anonymous:!0,expiresAt:state.expiresAt,claimUrl:state.claimUrl,org:{type:"user",id:"",slug:"anonymous"},project:{id:state.projectId,name:state.projectId}}}function validateAnonymousTarget(isAnonymous,target){return isAnonymous&&target&&target!=="production"?(output_manager_default.error(`Anonymous deployments always target production, so "${target}" is not available. Remove the ${param("--target")} option, or run ${getCommandName("login")} to deploy to other environments.`),!1):!0}async function setupAnonymousDeployment(client,cwd,{isAnonymous,dryRun}){isAnonymous||await clearAnonymousState(cwd);let anonymousLink;if(isAnonymous){let anonymous=await ensureAnonymousLink(client,cwd,{requireExistingState:dryRun});if(anonymous==="refused"){output_manager_default.log("Temporary deployments aren't available for this attempt. Log in to continue.");let{default:promptMissingCredentials}=await import("../../chunks/prompt-missing-credentials-C3OIQONK.js"),loginExitCode=await promptMissingCredentials(client);if(loginExitCode!==0)return loginExitCode;isAnonymous=!1}else{if(anonymous==="failed")return 1;if(anonymous==="confirmation-required")return 1;anonymousLink=anonymous}}return{isAnonymous,anonymousLink}}async function handleAnonymousDeploymentError({client,cwd,error,link,isV0,retry}){if(!(!link||!isAPIError(error))){if(error.code==="anonymous_project_claimed"){if(client.nonInteractive||!client.stdin.isTTY)return output_manager_default.prettyError({message:`This project was claimed successfully. Run ${getCommandName("login")} to continue deploying it.`}),1;output_manager_default.log("This project was claimed successfully. Log in to continue deploying it.");let loginExitCode;try{let{default:login}=await import("../../chunks/login-PFAKA6JO.js");loginExitCode=await login(client,{shouldParseArgs:!1})}catch(loginError){return printError(loginError),1}if(loginExitCode!==0)return loginExitCode;let claimedProjectLink=await ensureLink("deploy",client,cwd,{autoConfirm:!0,projectName:link.project.id,failIfNotFound:!0,allowOwnerLookupFallback:!0,v0:isV0});return typeof claimedProjectLink=="number"?claimedProjectLink:(await linkFolderToProject(client,cwd,{projectId:claimedProjectLink.project.id,orgId:claimedProjectLink.org.id},claimedProjectLink.project.name,claimedProjectLink.org.slug,"link",!0,!1),await clearAnonymousState(cwd),retry())}if(error.status===401||error.status===410)return await clearAnonymousState(cwd),output_manager_default.prettyError({message:`Your temporary deployment has expired. Run ${getCommandName("login")} to create an account and keep deploying this app.`}),1}}async function runImplicitBuild(client,cwd){let projectJsonPath=join12(cwd,VERCEL_DIR,VERCEL_DIR_PROJECT),projectJsonExists=await import_fs_extra3.default.pathExists(projectJsonPath);projectJsonExists||await import_fs_extra3.default.outputJSON(projectJsonPath,{settings:{}},{spaces:2}),await import_fs_extra3.default.pathExists(join12(cwd,"package.json"))&&output_manager_default.log("Building your project locally\u2026");let originalArgv=client.argv,originalCwd=client.cwd,originalStdout=client.stdout,previousVercelFirstDeployment=process.env.VERCEL_FIRST_DEPLOYMENT;client.cwd=cwd,client.setArgv([...originalArgv.slice(0,2),"build","--prod","--yes"]),process.env.VERCEL_FIRST_DEPLOYMENT="1",client.stdout=createSinkStream();try{let build=(await import("../build/index.js")).default;return await build(client)}finally{client.setArgv(originalArgv),client.cwd=originalCwd,client.stdout=originalStdout,previousVercelFirstDeployment===void 0?delete process.env.VERCEL_FIRST_DEPLOYMENT:process.env.VERCEL_FIRST_DEPLOYMENT=previousVercelFirstDeployment,projectJsonExists||await import_fs_extra3.default.remove(projectJsonPath)}}function createSinkStream(){return{isTTY:!1,write:()=>!0}}var COMMAND_CONFIG={init:getCommandAliases(initSubcommand),continue:getCommandAliases(continueSubcommand),describe:getCommandAliases(describeSubcommand)},deploy_default=async client=>{let telemetryClient=new DeployTelemetryClient({opts:{store:client.telemetryEventStore}}),parsedArguments=null,flagsSpecification=getFlagsSpecification(deployCommand.options);try{parsedArguments=parseArguments(client.argv.slice(2),flagsSpecification,{permissive:!0})}catch(error){return printError(error),2}let subArgs=parsedArguments.args[0]===deployCommand.name?parsedArguments.args.slice(1):parsedArguments.args,{subcommand,subcommandOriginal}=getSubcommand(subArgs,COMMAND_CONFIG);function printSubcommandHelp(command){output_manager_default.print(help(command,{parent:deployCommand,columns:client.stderr.columns}))}switch(subcommand){case"init":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(initSubcommand),0):(telemetryClient.trackCliSubcommandInit(subcommandOriginal),handleInitDeployment(client,telemetryClient));case"continue":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(continueSubcommand),0):(telemetryClient.trackCliSubcommandContinue(subcommandOriginal),handleContinueSubcommand(client,telemetryClient));case"describe":return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy",subcommandOriginal),printSubcommandHelp(describeSubcommand),0):(telemetryClient.trackCliSubcommandDescribe(subcommandOriginal),describe(client));default:return parsedArguments.flags["--help"]?(telemetryClient.trackCliFlagHelp("deploy"),output_manager_default.print(help(deployCommand,{columns:client.stderr.columns})),0):handleDefaultDeploy(client,telemetryClient)}};async function handleInitDeployment(client,telemetryClient){let flagsSpecification=getFlagsSpecification(initSubcommand.options),parsedArguments;try{parsedArguments=parseArguments(client.argv.slice(2),flagsSpecification)}catch(error2){return printError(error2),2}telemetryClient.trackCliFlagJson(parsedArguments.flags["--json"]),telemetryClient.trackCliOptionFormat(parsedArguments.flags["--format"]),telemetryClient.trackCliOptionProject(parsedArguments.flags["--project"]);let projectNameOrId=parsedArguments.flags["--project"],formatResult=validateJsonOutput(parsedArguments.flags);if(!formatResult.valid)return output_manager_default.error(formatResult.error),2;let asJson=formatResult.jsonOutput||client.nonInteractive,args=parsedArguments.args;args[0]==="deploy"&&(args=args.slice(1)),args[0]==="init"&&(args=args.slice(1));let paths;args.length>0?(paths=args.map(item=>resolve3(client.cwd,item)),telemetryClient.trackCliArgumentProjectPath(paths[0])):paths=[client.cwd];let pathValidation=await validatePaths(client,paths);if(!pathValidation.valid)return pathValidation.exitCode;await compileVercelConfig(paths[0]);let localConfig=paths[0]===client.cwd?client.localConfig||readLocalConfig(paths[0]):readLocalConfig(paths[0]);if(localConfig){client.localConfig=localConfig;let{version}=localConfig,file=highlight(localConfig[import_client.fileNameSymbol]),prop=code("version");if(version)if(typeof version=="number"){if(version!==2){let two=code(String(2));return output_manager_default.error(`The value of the ${prop} property within ${file} can only be ${two}.`),1}}else return output_manager_default.error(`The ${prop} property inside your ${file} file must be a number.`),1}let{log,debug,error}=output_manager_default,quiet=!client.stdout.isTTY,{path:cwd}=pathValidation,autoConfirm=parsedArguments.flags["--yes"],target=parseTarget({flagName:"target",flags:parsedArguments.flags});telemetryClient.trackTargetEnvironment(target);let parsedArchive=parsedArguments.flags["--archive"];if(typeof parsedArchive=="string"&&!(isValidArchive(parsedArchive)||parsedArchive===deprecatedArchiveSplitTgz))return output_manager_default.error(`Format must be one of: ${import_client.VALID_ARCHIVE_FORMATS.join(", ")}`),2;parsedArchive===deprecatedArchiveSplitTgz&&output_manager_default.print(`${prependEmoji(`${param("--archive=tgz")} now has the same behavior as ${param("--archive=split-tgz")}. Please use ${param("--archive=tgz")} instead.`,emoji("warning"))}
|
|
24
24
|
`);let cliMeta=parseMeta(parsedArguments.flags["--meta"]),isV0=cliMeta.v0==="true";getGitExecutable(cwd);let link=await ensureLink("deploy",client,cwd,{autoConfirm,projectName:projectNameOrId??localConfig?.name,failIfNotFound:!!projectNameOrId,v0:isV0});if(typeof link=="number")return link;let{org,project}=link,rootDirectory=project.rootDirectory,sourceFilesOutsideRootDirectory=project.sourceFilesOutsideRootDirectory??!0;link.repoRoot&&(cwd=link.repoRoot);let contextName=org.slug;if(client.config.currentTeam=org.type==="team"?org.id:void 0,rootDirectory&&await validateRootDirectory(cwd,join13(cwd,rootDirectory),project?`To change your Project Settings, go to https://vercel.com/${org?.slug}/${project.name}/settings`:"")===!1)return 1;if(await promptExperimentalServicesMigration({client,cwd:join13(cwd,rootDirectory||""),autoConfirm:!!parsedArguments.flags["--yes"],nonInteractive:client.nonInteractive})&&(localConfig=readLocalConfig(join13(cwd,rootDirectory||""))),rootDirectory){let rootDirectoryPath=join13(cwd,rootDirectory);await compileVercelConfig(rootDirectoryPath);let rootDirectoryConfig=readLocalConfig(rootDirectoryPath);rootDirectoryConfig?(debug(`Read local config from root directory (${rootDirectory})`),localConfig=rootDirectoryConfig):localConfig&&output_manager_default.print(`${prependEmoji(`The ${highlight(localConfig[import_client.fileNameSymbol])} file should be inside of the provided root directory.`,emoji("warning"))}
|
|
25
25
|
`)}localConfig=localConfig||{},localConfig.name&&output_manager_default.print(`${prependEmoji(`The ${code("name")} property in ${highlight(localConfig[import_client.fileNameSymbol])} is deprecated (https://vercel.link/name-prop)`,emoji("warning"))}
|
|
26
26
|
`);let isObject=item=>Object.prototype.toString.call(item)==="[object Object]";if(typeof localConfig.env<"u"&&!isObject(localConfig.env))return error(`The ${code("env")} property in ${highlight(localConfig[import_client.fileNameSymbol])} needs to be an object`),1;if(typeof localConfig.build<"u"){if(!isObject(localConfig.build))return error(`The ${code("build")} property in ${highlight(localConfig[import_client.fileNameSymbol])} needs to be an object`),1;if(typeof localConfig.build.env<"u"&&!isObject(localConfig.build.env))return error(`The ${code("build.env")} property in ${highlight(localConfig[import_client.fileNameSymbol])} needs to be an object`),1}let meta=Object.assign({},parseMeta(localConfig.meta),cliMeta),gitMetadata=createGitMeta(join13(cwd,project.rootDirectory||""),project);gitMetadata.catch(()=>{});let deploymentEnv=Object.assign({},parseEnv(localConfig.env),parseEnv(parsedArguments.flags["--env"])),deploymentBuildEnv=Object.assign({},parseEnv(localConfig.build&&localConfig.build.env),parseEnv(parsedArguments.flags["--build-env"]));try{await addProcessEnv(log,deploymentEnv),await addProcessEnv(log,deploymentBuildEnv)}catch(err){return error((0,import_error_utils2.errorToString)(err)),1}let regionFlag=(parsedArguments.flags["--regions"]||"").split(",").map(s=>s.trim()).filter(Boolean),regions=regionFlag.length>0?regionFlag:localConfig.regions,currentTeam=org.type==="team"?org.id:void 0,now=new Now({client,currentTeam}),deployStamp=stamp_default(),localConfigurationOverrides=pickOverrides(localConfig),name=project.name;if(!name)throw new Error("`name` not found on project or provided by existing project");let noWait=!0;try{let autoAssignCustomDomains=parsedArguments.flags["--skip-domain"]?!1:void 0,createArgs={name,env:deploymentEnv,build:{env:deploymentBuildEnv},forceNew:parsedArguments.flags["--force"],withCache:parsedArguments.flags["--with-cache"],prebuilt:!0,vercelOutputDir:void 0,rootDirectory,quiet,nowConfig:{...localConfig,images:void 0},regions,meta,gitMetadata,deployStamp,target,skipAutoDetectionConfirmation:autoConfirm,noWait,withFullLogs:!1,autoAssignCustomDomains,manual:!0,jsonOutput:asJson,linkedProject:project};(!localConfig.builds||localConfig.builds.length===0)&&(createArgs.projectSettings={sourceFilesOutsideRootDirectory,rootDirectory,...localConfigurationOverrides});let{packageJson}=await(0,import_build_utils9.findPackageJson)(join13(cwd,project?.rootDirectory??""),!0,cwd),nodeVersion;if(packageJson?.engines?.node)try{let{range}=await(0,import_build_utils9.getSupportedNodeVersion)(packageJson.engines.node);nodeVersion=range}catch(error2){error2 instanceof Error&&output_manager_default.warn(error2.message)}createArgs.projectSettings||(createArgs.projectSettings={}),createArgs.projectSettings.nodeVersion=nodeVersion;let deployment=await createDeploy(client,now,contextName,cwd,createArgs,org,!project,parsedArchive?"tgz":void 0);if(deployment instanceof NotDomainOwner)return recordCliError({code:"not_domain_owner"}),client.nonInteractive?(client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"not_domain_owner",message:deployment.message,next:[{command:withGlobalFlags(client,"deploy"),when:"retry deploy"}]},null,2)}
|
|
@@ -49,9 +49,9 @@ ${err.stack}`),err instanceof UploadErrorMissingArchive)return output_manager_de
|
|
|
49
49
|
`),1):(error("Uploading failed. Please try again."),1)}catch(err){recordCliError(cliErrorFromUnknown(err)),(0,import_error_utils2.isError)(err)&&debug(`Error: ${err}
|
|
50
50
|
${err.stack}`);let anonymousExitCode=await handleAnonymousDeploymentError({client,cwd,error:err,link:anonymousLink,isV0,retry:()=>handleDefaultDeploy(client,telemetryClient)});if(anonymousExitCode!==void 0)return anonymousExitCode;if(err instanceof UploadErrorMissingArchive)return client.nonInteractive?(client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"missing_archive",message:err.message,next:[{command:redeployCommand,when:"retry deploy"}]},null,2)}
|
|
51
51
|
`),1):(output_manager_default.prettyError(err),1);if(err instanceof NotDomainOwner)return recordCliError({code:"not_domain_owner"},{override:!0}),client.nonInteractive?(client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"not_domain_owner",message:err.message,next:[{command:redeployCommand,when:"retry deploy"}]},null,2)}
|
|
52
|
-
`),1):(output_manager_default.error(err.message),1);if(err instanceof DomainNotFound&&err.meta&&err.meta.domain){output_manager_default.debug(`The domain ${err.meta.domain} was not found, trying to purchase it`);let{default:purchaseDomainIfAvailable}=await import("../../chunks/purchase-domain-if-available-
|
|
52
|
+
`),1):(output_manager_default.error(err.message),1);if(err instanceof DomainNotFound&&err.meta&&err.meta.domain){output_manager_default.debug(`The domain ${err.meta.domain} was not found, trying to purchase it`);let{default:purchaseDomainIfAvailable}=await import("../../chunks/purchase-domain-if-available-QBDRKJZ5.js"),purchase=await purchaseDomainIfAvailable(client,err.meta.domain,contextName);return purchase===!0?(output_manager_default.success(`Successfully purchased the domain ${err.meta.domain}!`),0):purchase===!1||purchase instanceof UserAborted?(handleCreateDeployError(deployment,localConfig),1):(handleCreateDeployError(purchase,localConfig)!==1&&output_manager_default.error(purchase.message),1)}if(err instanceof DomainNotFound||err instanceof DomainNotVerified||err instanceof NotDomainOwner||err instanceof DomainPermissionDenied||err instanceof DomainVerificationFailed||err instanceof SchemaValidationFailed||err instanceof InvalidDomain||err instanceof DeploymentNotFound||err instanceof BuildsRateLimited||err instanceof DeploymentsRateLimited||err instanceof AliasDomainConfigured||err instanceof MissingBuildScript||err instanceof ConflictingFilePath||err instanceof ConflictingPathSegment||err instanceof ConflictingConfigFiles)return client.nonInteractive&&client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"deploy_failed",message:err instanceof Error?err.message:String(err),next:[{command:redeployCommand,when:"retry deploy"}]},null,2)}
|
|
53
53
|
`),handleCreateDeployError(err,localConfig),1;if(err instanceof BuildError){let buildFailedNext=[...now.url?[{command:withGlobalFlags(client,`inspect ${now.url} --logs`),when:"read build logs"}]:[],{command:redeployCommand,when:"retry deploy"}];if(now.url)try{let failedDeployment=await getDeployment(client,contextName,now.url);if(asJson){output_manager_default.stopSpinner();let deploymentJson=getDeploymentOutputJson(failedDeployment,client.apiUrl,{name:"BUILD_ERROR",message:err.message}),payload=client.nonInteractive?{status:AGENT_STATUS.ERROR,reason:"build_failed",message:err.message,deployment:deploymentJson,next:buildFailedNext}:deploymentJson;client.stdout.write(`${JSON.stringify(payload,null,2)}
|
|
54
|
-
`)}else if(withFullLogs===!1){let{displayBuildLogsUntilFinalError}=await import("../../chunks/logs-
|
|
54
|
+
`)}else if(withFullLogs===!1){let{displayBuildLogsUntilFinalError}=await import("../../chunks/logs-4FOJKWAW.js");await displayBuildLogsUntilFinalError(client,failedDeployment,err.message)}}catch{if(asJson){output_manager_default.stopSpinner();let payload=client.nonInteractive?{status:AGENT_STATUS.ERROR,reason:"build_failed",message:err.message,url:`https://${now.url}`,next:buildFailedNext}:{error:{name:"BUILD_ERROR",message:err.message},url:`https://${now.url}`};client.stdout.write(`${JSON.stringify(payload,null,2)}
|
|
55
55
|
`)}else output_manager_default.log(`To check build logs run: ${getCommandName(`inspect ${now.url} --logs`)}`),output_manager_default.log(`Or inspect them in your browser at https://${now.url}/_logs`)}else client.nonInteractive&&(output_manager_default.stopSpinner(),client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"build_failed",message:err.message,next:buildFailedNext},null,2)}
|
|
56
56
|
`));return 1}if(isAPIError(err)&&err.code==="size_limit_exceeded"){let{sizeLimit=0}=err,message=`File size limit exceeded (${(0,import_bytes.default)(sizeLimit)})`;return client.nonInteractive&&client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"size_limit_exceeded",message,next:[{command:redeployCommand,when:"retry deploy"}]},null,2)}
|
|
57
57
|
`),error(message),1}return client.nonInteractive&&client.stdout.write(`${JSON.stringify({status:AGENT_STATUS.ERROR,reason:"deploy_failed",message:err instanceof Error?err.message:String(err),next:[{command:redeployCommand,when:"retry deploy"}]},null,2)}
|
|
@@ -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-XJOOPPSQ.js";import{loadVercelConfig,tryDetectServices}from"../../chunks/chunk-TKA7PPGY.js";import"../../chunks/chunk-7V2F5IUY.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-VJEQAITW.js";import{importBuilders,require_npa}from"../../chunks/chunk-JTAAWOJS.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-NZBUIMZG.js";import"../../chunks/chunk-QHJLRTVY.js";import{require_fast_deep_equal}from"../../chunks/chunk-MCRKBVZA.js";import{getUpdateCommand}from"../../chunks/chunk-JUSQYKFF.js";import{readJSONFile}from"../../chunks/chunk-BRUTDRAQ.js";import"../../chunks/chunk-YLTCVZOL.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-H7LHZZKU.js";import{validateConfig}from"../../chunks/chunk-MZ6DNAVL.js";import"../../chunks/chunk-BZYQ6RFV.js";import"../../chunks/chunk-EAUDC24V.js";import{pickOverrides}from"../../chunks/chunk-WF5YVWWY.js";import{require_dist as require_dist5}from"../../chunks/chunk-YAPHSZJ7.js";import{require_brace_expansion,require_dist as require_dist3,require_dist2 as require_dist4,require_minimatch}from"../../chunks/chunk-WJ4VNTE3.js";import{require_main}from"../../chunks/chunk-VOB4W7DO.js";import"../../chunks/chunk-RRDNKB2X.js";import"../../chunks/chunk-MVGTMPMI.js";import"../../chunks/chunk-SACGQMVQ.js";import"../../chunks/chunk-BPUANOGW.js";import"../../chunks/chunk-3E364MJE.js";import{require_inherits}from"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-P2O5DOYE.js";import"../../chunks/chunk-GSOPJJO5.js";import{VERCEL_OIDC_TOKEN}from"../../chunks/chunk-BWY67LI6.js";import"../../chunks/chunk-IAUAFUO2.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-3AF3TTCR.js";import{printProjectNotFoundError}from"../../chunks/chunk-QW2UP4W4.js";import"../../chunks/chunk-KTNRWBHM.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-S7XZC23O.js";import{require_dist as require_dist2}from"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-HJ3NY4UA.js";import"../../chunks/chunk-2H243SJV.js";import"../../chunks/chunk-SCV7XEEO.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-3EYOQC4R.js";import"../../chunks/chunk-XEQT373M.js";import"../../chunks/chunk-VIBUYIZ3.js";import"../../chunks/chunk-6LRVRPYO.js";import{help}from"../../chunks/chunk-7D2HVBVP.js";import"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-V336CYEI.js";import{buildCommandWithYes,outputActionRequired}from"../../chunks/chunk-5RR3435W.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{detectExplicitScope,getLocalPathConfig,highlight}from"../../chunks/chunk-DZ6GORJ7.js";import{getGlobalPathConfig}from"../../chunks/chunk-HMS3UIQ2.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{TelemetryClient}from"../../chunks/chunk-HUJPGK7W.js";import"../../chunks/chunk-VKXEOL4K.js";import{isNativeBinaryInstall}from"../../chunks/chunk-YYPNUQDI.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-R4VVQRLX.js";import"../../chunks/chunk-BKV35LVB.js";import{getFlagsSpecification}from"../../chunks/chunk-5IPBCD7K.js";import{VERCEL_DIR,findRepoRoot,getLinkedProject,getVercelDirectory,require_lib,require_pluralize,resolveProjectCwd}from"../../chunks/chunk-MYMM34ZH.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import{printAlignedLabel}from"../../chunks/chunk-N7Q2IESO.js";import"../../chunks/chunk-VSE5BAPP.js";import"../../chunks/chunk-VOZEB6PD.js";import{CantParseJSONFile,LambdaSizeExceededError,MissingDotenvVarsError,NowError,require_bytes}from"../../chunks/chunk-AZULOP7M.js";import{cmd,getCommandName,getCommandNamePlain,getTitleName}from"../../chunks/chunk-JESNVRVR.js";import{Diagnostic,defineDiagnostics,init_dist,link_default,output_manager_default,require_build_utils}from"../../chunks/chunk-75IAMKGV.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import{pkg_default}from"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import{require_supports_color}from"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__commonJS,__require,__toESM}from"../../chunks/chunk-BZENIQ7N.js";var require_bytes2=__commonJS({"../../node_modules/.pnpm/bytes@3.1.0/node_modules/bytes/index.js"(exports2,module2){"use strict";module2.exports=bytes2;module2.exports.format=format;module2.exports.parse=parse2;var formatThousandsRegExp=/\B(?=(\d{3})+(?!\d))/g,formatDecimalsRegExp=/(?:\.0*|(\.[^0]+)0+)$/,map={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},parseRegExp=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function bytes2(value,options){return typeof value=="string"?parse2(value):typeof value=="number"?format(value,options):null}function format(value,options){if(!Number.isFinite(value))return null;var mag=Math.abs(value),thousandsSeparator=options&&options.thousandsSeparator||"",unitSeparator=options&&options.unitSeparator||"",decimalPlaces=options&&options.decimalPlaces!==void 0?options.decimalPlaces:2,fixedDecimals=!!(options&&options.fixedDecimals),unit=options&&options.unit||"";(!unit||!map[unit.toLowerCase()])&&(mag>=map.pb?unit="PB":mag>=map.tb?unit="TB":mag>=map.gb?unit="GB":mag>=map.mb?unit="MB":mag>=map.kb?unit="KB":unit="B");var val=value/map[unit.toLowerCase()],str=val.toFixed(decimalPlaces);return fixedDecimals||(str=str.replace(formatDecimalsRegExp,"$1")),thousandsSeparator&&(str=str.replace(formatThousandsRegExp,thousandsSeparator)),str+unitSeparator+unit}function parse2(val){if(typeof val=="number"&&!isNaN(val))return val;if(typeof val!="string")return null;var results=parseRegExp.exec(val),floatValue,unit="b";return results?(floatValue=parseFloat(results[1]),unit=results[4].toLowerCase()):(floatValue=parseInt(val,10),unit="b"),Math.floor(map[unit]*floatValue)}}});var require_callsite_tostring=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/lib/compat/callsite-tostring.js"(exports2,module2){"use strict";module2.exports=callSiteToString2;function callSiteFileLocation(callSite){var fileName,fileLocation="";if(callSite.isNative()?fileLocation="native":callSite.isEval()?(fileName=callSite.getScriptNameOrSourceURL(),fileName||(fileLocation=callSite.getEvalOrigin())):fileName=callSite.getFileName(),fileName){fileLocation+=fileName;var lineNumber=callSite.getLineNumber();if(lineNumber!=null){fileLocation+=":"+lineNumber;var columnNumber=callSite.getColumnNumber();columnNumber&&(fileLocation+=":"+columnNumber)}}return fileLocation||"unknown source"}function callSiteToString2(callSite){var addSuffix=!0,fileLocation=callSiteFileLocation(callSite),functionName=callSite.getFunctionName(),isConstructor=callSite.isConstructor(),isMethodCall=!(callSite.isToplevel()||isConstructor),line="";if(isMethodCall){var methodName=callSite.getMethodName(),typeName=getConstructorName(callSite);functionName?(typeName&&functionName.indexOf(typeName)!==0&&(line+=typeName+"."),line+=functionName,methodName&&functionName.lastIndexOf("."+methodName)!==functionName.length-methodName.length-1&&(line+=" [as "+methodName+"]")):line+=typeName+"."+(methodName||"<anonymous>")}else isConstructor?line+="new "+(functionName||"<anonymous>"):functionName?line+=functionName:(addSuffix=!1,line+=fileLocation);return addSuffix&&(line+=" ("+fileLocation+")"),line}function getConstructorName(obj){var receiver=obj.receiver;return receiver.constructor&&receiver.constructor.name||null}}});var require_event_listener_count=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/lib/compat/event-listener-count.js"(exports2,module2){"use strict";module2.exports=eventListenerCount2;function eventListenerCount2(emitter,type){return emitter.listeners(type).length}}});var require_compat=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/lib/compat/index.js"(exports2,module2){"use strict";var EventEmitter=__require("events").EventEmitter;lazyProperty(module2.exports,"callSiteToString",function(){var limit=Error.stackTraceLimit,obj={},prep=Error.prepareStackTrace;function prepareObjectStackTrace2(obj2,stack3){return stack3}Error.prepareStackTrace=prepareObjectStackTrace2,Error.stackTraceLimit=2,Error.captureStackTrace(obj);var stack2=obj.stack.slice();return Error.prepareStackTrace=prep,Error.stackTraceLimit=limit,stack2[0].toString?toString:require_callsite_tostring()});lazyProperty(module2.exports,"eventListenerCount",function(){return EventEmitter.listenerCount||require_event_listener_count()});function lazyProperty(obj,prop,getter){function get(){var val=getter();return Object.defineProperty(obj,prop,{configurable:!0,enumerable:!0,value:val}),val}Object.defineProperty(obj,prop,{configurable:!0,enumerable:!0,get})}function toString(obj){return obj.toString()}}});var require_depd=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/index.js"(exports,module){var callSiteToString=require_compat().callSiteToString,eventListenerCount=require_compat().eventListenerCount,relative=__require("path").relative;module.exports=depd;var basePath=process.cwd();function containsNamespace(str,namespace){for(var vals=str.split(/[ ,]+/),ns=String(namespace).toLowerCase(),i=0;i<vals.length;i++){var val=vals[i];if(val&&(val==="*"||val.toLowerCase()===ns))return!0}return!1}function convertDataDescriptorToAccessor(obj,prop,message2){var descriptor=Object.getOwnPropertyDescriptor(obj,prop),value=descriptor.value;return descriptor.get=function(){return value},descriptor.writable&&(descriptor.set=function(val){return value=val}),delete descriptor.value,delete descriptor.writable,Object.defineProperty(obj,prop,descriptor),descriptor}function createArgumentsString(arity){for(var str="",i=0;i<arity;i++)str+=", arg"+i;return str.substr(2)}function createStackString(stack2){var str=this.name+": "+this.namespace;this.message&&(str+=" deprecated "+this.message);for(var i=0;i<stack2.length;i++)str+=`
|
|
7
|
+
import{displayDetectedServices,readConfig,setupAndLink}from"../../chunks/chunk-NUITF4GR.js";import{loadVercelConfig,tryDetectServices}from"../../chunks/chunk-BIFAR2CO.js";import"../../chunks/chunk-7V2F5IUY.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-RV77ZW7T.js";import{importBuilders,require_npa}from"../../chunks/chunk-IMC63GXI.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-EDVP7QUI.js";import"../../chunks/chunk-QHJLRTVY.js";import{require_fast_deep_equal}from"../../chunks/chunk-MCRKBVZA.js";import{getUpdateCommand}from"../../chunks/chunk-3TJDVDDJ.js";import{readJSONFile}from"../../chunks/chunk-VLSSMFTF.js";import"../../chunks/chunk-6TEFVB2U.js";import{promptExperimentalServicesMigration}from"../../chunks/chunk-Y35RMGOU.js";import{validateConfig}from"../../chunks/chunk-MZ6DNAVL.js";import"../../chunks/chunk-SYEKOJHT.js";import"../../chunks/chunk-EAUDC24V.js";import{pickOverrides}from"../../chunks/chunk-FU7KGU6V.js";import{require_dist as require_dist5}from"../../chunks/chunk-YAPHSZJ7.js";import{require_brace_expansion,require_dist as require_dist3,require_dist2 as require_dist4,require_minimatch}from"../../chunks/chunk-WJ4VNTE3.js";import{require_main}from"../../chunks/chunk-SZRSBECO.js";import"../../chunks/chunk-RRDNKB2X.js";import"../../chunks/chunk-MVGTMPMI.js";import"../../chunks/chunk-SACGQMVQ.js";import"../../chunks/chunk-BPUANOGW.js";import"../../chunks/chunk-3E364MJE.js";import{require_inherits}from"../../chunks/chunk-7EJQLVWX.js";import"../../chunks/chunk-P2O5DOYE.js";import"../../chunks/chunk-GSOPJJO5.js";import{VERCEL_OIDC_TOKEN}from"../../chunks/chunk-ZH4DW3T3.js";import"../../chunks/chunk-K5GYV5CW.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-7SGM233C.js";import{printProjectNotFoundError}from"../../chunks/chunk-3YQVBYQD.js";import"../../chunks/chunk-I7FGFRN3.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-S7XZC23O.js";import{require_dist as require_dist2}from"../../chunks/chunk-JALVF3C2.js";import"../../chunks/chunk-FBYA6LLM.js";import"../../chunks/chunk-6LXX5P3A.js";import"../../chunks/chunk-MSH7V3FL.js";import"../../chunks/chunk-SCV7XEEO.js";import{param}from"../../chunks/chunk-3G3FQYMW.js";import"../../chunks/chunk-3EYOQC4R.js";import"../../chunks/chunk-XEQT373M.js";import"../../chunks/chunk-J2LAZELI.js";import"../../chunks/chunk-E6UKNYFF.js";import{help}from"../../chunks/chunk-5O2CW3SX.js";import"../../chunks/chunk-773GOZIR.js";import{printError}from"../../chunks/chunk-T6GXMIXO.js";import{buildCommandWithYes,outputActionRequired}from"../../chunks/chunk-5YQP44VL.js";import"../../chunks/chunk-67GZ5REA.js";import"../../chunks/chunk-BS32OUOC.js";import{detectExplicitScope,getLocalPathConfig,highlight}from"../../chunks/chunk-HWYHRPWP.js";import{getGlobalPathConfig}from"../../chunks/chunk-HMS3UIQ2.js";import{require_ms}from"../../chunks/chunk-MXTC4ZAQ.js";import{TelemetryClient}from"../../chunks/chunk-TNZMCRAP.js";import"../../chunks/chunk-VKXEOL4K.js";import{isNativeBinaryInstall}from"../../chunks/chunk-YYPNUQDI.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-R4VVQRLX.js";import"../../chunks/chunk-BKV35LVB.js";import{getFlagsSpecification}from"../../chunks/chunk-5IPBCD7K.js";import{VERCEL_DIR,findRepoRoot,getLinkedProject,getVercelDirectory,require_lib,require_pluralize,resolveProjectCwd}from"../../chunks/chunk-SWJYZETA.js";import"../../chunks/chunk-ROPQIBWJ.js";import"../../chunks/chunk-VKPZP4LC.js";import"../../chunks/chunk-PPCFQQSU.js";import{printAlignedLabel}from"../../chunks/chunk-N7Q2IESO.js";import"../../chunks/chunk-WPQN5UKR.js";import"../../chunks/chunk-VOZEB6PD.js";import{CantParseJSONFile,LambdaSizeExceededError,MissingDotenvVarsError,NowError,require_bytes}from"../../chunks/chunk-YIIPBH2D.js";import{cmd,getCommandName,getCommandNamePlain,getTitleName}from"../../chunks/chunk-JESNVRVR.js";import{Diagnostic,defineDiagnostics,init_dist,link_default,output_manager_default,require_build_utils}from"../../chunks/chunk-75IAMKGV.js";import{require_dist}from"../../chunks/chunk-RM3ZDRYE.js";import{pkg_default}from"../../chunks/chunk-OO572JUC.js";import"../../chunks/chunk-D3AHZ5LI.js";import"../../chunks/chunk-2GHZGOWT.js";import"../../chunks/chunk-YHPPP3SF.js";import{require_source}from"../../chunks/chunk-NB2WLB3J.js";import{require_supports_color}from"../../chunks/chunk-ISWW3DKF.js";import"../../chunks/chunk-BRQUZ5NC.js";import{__commonJS,__require,__toESM}from"../../chunks/chunk-BZENIQ7N.js";var require_bytes2=__commonJS({"../../node_modules/.pnpm/bytes@3.1.0/node_modules/bytes/index.js"(exports2,module2){"use strict";module2.exports=bytes2;module2.exports.format=format;module2.exports.parse=parse2;var formatThousandsRegExp=/\B(?=(\d{3})+(?!\d))/g,formatDecimalsRegExp=/(?:\.0*|(\.[^0]+)0+)$/,map={b:1,kb:1024,mb:1<<20,gb:1<<30,tb:Math.pow(1024,4),pb:Math.pow(1024,5)},parseRegExp=/^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i;function bytes2(value,options){return typeof value=="string"?parse2(value):typeof value=="number"?format(value,options):null}function format(value,options){if(!Number.isFinite(value))return null;var mag=Math.abs(value),thousandsSeparator=options&&options.thousandsSeparator||"",unitSeparator=options&&options.unitSeparator||"",decimalPlaces=options&&options.decimalPlaces!==void 0?options.decimalPlaces:2,fixedDecimals=!!(options&&options.fixedDecimals),unit=options&&options.unit||"";(!unit||!map[unit.toLowerCase()])&&(mag>=map.pb?unit="PB":mag>=map.tb?unit="TB":mag>=map.gb?unit="GB":mag>=map.mb?unit="MB":mag>=map.kb?unit="KB":unit="B");var val=value/map[unit.toLowerCase()],str=val.toFixed(decimalPlaces);return fixedDecimals||(str=str.replace(formatDecimalsRegExp,"$1")),thousandsSeparator&&(str=str.replace(formatThousandsRegExp,thousandsSeparator)),str+unitSeparator+unit}function parse2(val){if(typeof val=="number"&&!isNaN(val))return val;if(typeof val!="string")return null;var results=parseRegExp.exec(val),floatValue,unit="b";return results?(floatValue=parseFloat(results[1]),unit=results[4].toLowerCase()):(floatValue=parseInt(val,10),unit="b"),Math.floor(map[unit]*floatValue)}}});var require_callsite_tostring=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/lib/compat/callsite-tostring.js"(exports2,module2){"use strict";module2.exports=callSiteToString2;function callSiteFileLocation(callSite){var fileName,fileLocation="";if(callSite.isNative()?fileLocation="native":callSite.isEval()?(fileName=callSite.getScriptNameOrSourceURL(),fileName||(fileLocation=callSite.getEvalOrigin())):fileName=callSite.getFileName(),fileName){fileLocation+=fileName;var lineNumber=callSite.getLineNumber();if(lineNumber!=null){fileLocation+=":"+lineNumber;var columnNumber=callSite.getColumnNumber();columnNumber&&(fileLocation+=":"+columnNumber)}}return fileLocation||"unknown source"}function callSiteToString2(callSite){var addSuffix=!0,fileLocation=callSiteFileLocation(callSite),functionName=callSite.getFunctionName(),isConstructor=callSite.isConstructor(),isMethodCall=!(callSite.isToplevel()||isConstructor),line="";if(isMethodCall){var methodName=callSite.getMethodName(),typeName=getConstructorName(callSite);functionName?(typeName&&functionName.indexOf(typeName)!==0&&(line+=typeName+"."),line+=functionName,methodName&&functionName.lastIndexOf("."+methodName)!==functionName.length-methodName.length-1&&(line+=" [as "+methodName+"]")):line+=typeName+"."+(methodName||"<anonymous>")}else isConstructor?line+="new "+(functionName||"<anonymous>"):functionName?line+=functionName:(addSuffix=!1,line+=fileLocation);return addSuffix&&(line+=" ("+fileLocation+")"),line}function getConstructorName(obj){var receiver=obj.receiver;return receiver.constructor&&receiver.constructor.name||null}}});var require_event_listener_count=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/lib/compat/event-listener-count.js"(exports2,module2){"use strict";module2.exports=eventListenerCount2;function eventListenerCount2(emitter,type){return emitter.listeners(type).length}}});var require_compat=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/lib/compat/index.js"(exports2,module2){"use strict";var EventEmitter=__require("events").EventEmitter;lazyProperty(module2.exports,"callSiteToString",function(){var limit=Error.stackTraceLimit,obj={},prep=Error.prepareStackTrace;function prepareObjectStackTrace2(obj2,stack3){return stack3}Error.prepareStackTrace=prepareObjectStackTrace2,Error.stackTraceLimit=2,Error.captureStackTrace(obj);var stack2=obj.stack.slice();return Error.prepareStackTrace=prep,Error.stackTraceLimit=limit,stack2[0].toString?toString:require_callsite_tostring()});lazyProperty(module2.exports,"eventListenerCount",function(){return EventEmitter.listenerCount||require_event_listener_count()});function lazyProperty(obj,prop,getter){function get(){var val=getter();return Object.defineProperty(obj,prop,{configurable:!0,enumerable:!0,value:val}),val}Object.defineProperty(obj,prop,{configurable:!0,enumerable:!0,get})}function toString(obj){return obj.toString()}}});var require_depd=__commonJS({"../../node_modules/.pnpm/depd@1.1.2/node_modules/depd/index.js"(exports,module){var callSiteToString=require_compat().callSiteToString,eventListenerCount=require_compat().eventListenerCount,relative=__require("path").relative;module.exports=depd;var basePath=process.cwd();function containsNamespace(str,namespace){for(var vals=str.split(/[ ,]+/),ns=String(namespace).toLowerCase(),i=0;i<vals.length;i++){var val=vals[i];if(val&&(val==="*"||val.toLowerCase()===ns))return!0}return!1}function convertDataDescriptorToAccessor(obj,prop,message2){var descriptor=Object.getOwnPropertyDescriptor(obj,prop),value=descriptor.value;return descriptor.get=function(){return value},descriptor.writable&&(descriptor.set=function(val){return value=val}),delete descriptor.value,delete descriptor.writable,Object.defineProperty(obj,prop,descriptor),descriptor}function createArgumentsString(arity){for(var str="",i=0;i<arity;i++)str+=", arg"+i;return str.substr(2)}function createStackString(stack2){var str=this.name+": "+this.namespace;this.message&&(str+=" deprecated "+this.message);for(var i=0;i<stack2.length;i++)str+=`
|
|
8
8
|
at `+callSiteToString(stack2[i]);return str}function depd(namespace){if(!namespace)throw new TypeError("argument namespace is required");var stack2=getStack(),site2=callSiteLocation(stack2[1]),file=site2[0];function deprecate2(message2){log.call(deprecate2,message2)}return deprecate2._file=file,deprecate2._ignored=isignored(namespace),deprecate2._namespace=namespace,deprecate2._traced=istraced(namespace),deprecate2._warned=Object.create(null),deprecate2.function=wrapfunction,deprecate2.property=wrapproperty,deprecate2}function isignored(namespace){if(process.noDeprecation)return!0;var str=process.env.NO_DEPRECATION||"";return containsNamespace(str,namespace)}function istraced(namespace){if(process.traceDeprecation)return!0;var str=process.env.TRACE_DEPRECATION||"";return containsNamespace(str,namespace)}function log(message2,site2){var haslisteners=eventListenerCount(process,"deprecation")!==0;if(!(!haslisteners&&this._ignored)){var caller,callFile,callSite,depSite,i=0,seen=!1,stack2=getStack(),file=this._file;for(site2?(depSite=site2,callSite=callSiteLocation(stack2[1]),callSite.name=depSite.name,file=callSite[0]):(i=2,depSite=callSiteLocation(stack2[i]),callSite=depSite);i<stack2.length;i++)if(caller=callSiteLocation(stack2[i]),callFile=caller[0],callFile===file)seen=!0;else if(callFile===this._file)file=this._file;else if(seen)break;var key=caller?depSite.join(":")+"__"+caller.join(":"):void 0;if(!(key!==void 0&&key in this._warned)){this._warned[key]=!0;var msg=message2;if(msg||(msg=callSite===depSite||!callSite.name?defaultMessage(depSite):defaultMessage(callSite)),haslisteners){var err=DeprecationError(this._namespace,msg,stack2.slice(i));process.emit("deprecation",err);return}var format=process.stderr.isTTY?formatColor:formatPlain,output=format.call(this,msg,caller,stack2.slice(i));process.stderr.write(output+`
|
|
9
9
|
`,"utf8")}}}function callSiteLocation(callSite){var file=callSite.getFileName()||"<anonymous>",line=callSite.getLineNumber(),colm=callSite.getColumnNumber();callSite.isEval()&&(file=callSite.getEvalOrigin()+", "+file);var site2=[file,line,colm];return site2.callSite=callSite,site2.name=callSite.getFunctionName(),site2}function defaultMessage(site2){var callSite=site2.callSite,funcName=site2.name;funcName||(funcName="<anonymous@"+formatLocation(site2)+">");var context=callSite.getThis(),typeName=context&&callSite.getTypeName();return typeName==="Object"&&(typeName=void 0),typeName==="Function"&&(typeName=context.name||typeName),typeName&&callSite.getMethodName()?typeName+"."+funcName:funcName}function formatPlain(msg,caller,stack2){var timestamp=new Date().toUTCString(),formatted=timestamp+" "+this._namespace+" deprecated "+msg;if(this._traced){for(var i=0;i<stack2.length;i++)formatted+=`
|
|
10
10
|
at `+callSiteToString(stack2[i]);return formatted}return caller&&(formatted+=" at "+formatLocation(caller)),formatted}function formatColor(msg,caller,stack2){var formatted="\x1B[36;1m"+this._namespace+"\x1B[22;39m \x1B[33;1mdeprecated\x1B[22;39m \x1B[0m"+msg+"\x1B[39m";if(this._traced){for(var i=0;i<stack2.length;i++)formatted+=`
|
|
@@ -52,7 +52,7 @@ ${partHeaders}\r
|
|
|
52
52
|
`)))}parts.push(Uint8Array.from(Buffer.from(`--${boundary}--\r
|
|
53
53
|
`)));let body=Buffer.concat(parts);res.writeHead(200,{"Content-Type":`multipart/mixed; boundary=${boundary}`,"Content-Length":body.length}),res.end(body);return}let leaseMatch=topicPath.match(/^([A-Za-z0-9_-]+)\/consumer\/([A-Za-z0-9_-]+)\/lease\/([^/]+)(?:\/visibility)?$/);if(leaseMatch&&(req.method==="DELETE"||req.method==="PATCH")){let[,,consumer,receiptHandle]=leaseMatch,messageId=this.queueBroker.findMessageIdByReceiptHandle(consumer,receiptHandle);if(!messageId){res.writeHead(404,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Message not found"}));return}if(req.method==="DELETE"){this.queueBroker.acknowledge(messageId,consumer,receiptHandle),res.writeHead(204),res.end();return}let body=await(0,import_raw_body2.default)(req),timeoutSeconds=DEV_QUEUES_DEFAULT_VISIBILITY_TIMEOUT_SECONDS;try{let parsed=JSON.parse(body.toString());typeof parsed.visibilityTimeoutSeconds=="number"&&parsed.visibilityTimeoutSeconds>=0&&(timeoutSeconds=parsed.visibilityTimeoutSeconds)}catch(err){output_manager_default.debug(`queues: failed to parse visibility timeout body: ${err}`)}this.queueBroker.changeVisibility(messageId,consumer,receiptHandle,timeoutSeconds),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}res.writeHead(404),res.end("Not Found")};this.handleRuntimeCacheRoute=async(req,res,pathname)=>{let store=this.runtimeCache;if(!store){res.writeHead(503),res.end("Runtime Cache not initialized");return}if(!pathname.startsWith(DEV_RUNTIME_CACHE_API_PREFIX)){res.writeHead(404),res.end("Not Found");return}let itemPath=pathname.slice(DEV_RUNTIME_CACHE_API_PREFIX.length),searchParams=new URL2(req.url||"/","http://localhost").searchParams;if(itemPath==="revalidate"){if(req.method!=="POST"){res.writeHead(405),res.end("Method Not Allowed");return}let tags=(searchParams.get("tags")||"").split(",").map(tag=>tag.trim()).filter(Boolean),itemId=searchParams.get("itemId")||void 0;if(tags.length===0&&!itemId){res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"No tags or itemId provided"}));return}tags.length>0&&(store.expireTags(tags),output_manager_default.debug(`runtime cache: expired tags "${tags.join(",")}"`)),itemId&&(store.delete(itemId),output_manager_default.debug(`runtime cache: expired item "${itemId}"`)),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({revalidated:!0}));return}let key;try{key=decodeURIComponent(itemPath)}catch{res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid cache key"}));return}if(!key){res.writeHead(404),res.end("Not Found");return}if(req.method==="GET"){let hit=store.get(key);if(!hit){output_manager_default.debug(`runtime cache: MISS "${key}"`),res.writeHead(404),res.end("Not Found");return}output_manager_default.debug(`runtime cache: HIT "${key}"`);let headers={"Content-Type":"application/json","Content-Length":hit.value.length,[HEADER_CACHE_STATE]:"fresh",Age:String(hit.ageSeconds)};hit.tags.length>0&&(headers[HEADER_CACHE_TAGS]=hit.tags.join(",")),res.writeHead(200,headers),res.end(hit.value);return}if(req.method==="POST"){let revalidateHeader=req.headers[HEADER_REVALIDATE],ttlSeconds;if(revalidateHeader)if(revalidateHeader==="Infinity"||["false","False","FALSE","f","F"].includes(revalidateHeader))ttlSeconds=DEV_RUNTIME_CACHE_ONE_YEAR_SECONDS;else if(/^[+-]?\d+$/.test(revalidateHeader)){let parsedRevalidate=Number(revalidateHeader);if(!Number.isSafeInteger(parsedRevalidate)||parsedRevalidate<0){res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid revalidate value"}));return}if(parsedRevalidate===0){res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}ttlSeconds=parsedRevalidate}else{res.writeHead(400,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Invalid revalidate value"}));return}let value;try{value=await(0,import_raw_body2.default)(req,{limit:DEV_RUNTIME_CACHE_MAX_ITEM_SIZE})}catch(err){if(err.statusCode===413){res.writeHead(413,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Cache item is too large"}));return}throw err}let tagsHeader=req.headers[HEADER_CACHE_TAGS];store.set(key,value,{ttlSeconds,tags:(tagsHeader||"").split(",").map(tag=>tag.trim()).filter(Boolean)});let name=req.headers[HEADER_CACHE_ITEM_NAME];output_manager_default.debug(`runtime cache: SET "${key}"${name?` (${name})`:""} ${value.length} bytes`),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}if(req.method==="DELETE"){store.delete(key),output_manager_default.debug(`runtime cache: DELETE "${key}"`),res.writeHead(200,{"Content-Type":"application/json"}),res.end(JSON.stringify({success:!0}));return}res.writeHead(405),res.end("Method Not Allowed")};this.serveProjectAsNowV2=async(req,res,requestId,vercelConfig,routes=vercelConfig.routes,callLevel=0)=>{let{debug}=output_manager_default;if(callLevel===0&&await this.handleSchedulesProxyRequest(req,res))return;let parsed=url3.parse(req.url||"/");if(typeof parsed.pathname=="string"&&parsed.pathname.includes("//")){let location=parsed.pathname.replace(/\/+/g,"/");if(parsed.search&&(location+=parsed.search),req.method==="GET"){await this.sendRedirect(req,res,requestId,location,301);return}debug(`Rewriting URL from "${req.url}" to "${location}"`),req.url=location}let queueProxyPrefix=`${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`,runtimeCacheProxyPrefix=`${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}`;if(callLevel===0&&this.queueBroker){let pathname=parsed.pathname||"/";if(pathname.startsWith(`${queueProxyPrefix}/`)){if(!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}await this.handleQueuesRoute(req,res,pathname.slice(queueProxyPrefix.length));return}}if(callLevel===0){let pathname=parsed.pathname||"/";if(pathname.startsWith(`${runtimeCacheProxyPrefix}/`)){if(!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}await this.handleRuntimeCacheRoute(req,res,pathname.slice(runtimeCacheProxyPrefix.length));return}}if(callLevel===0&&this.bulkRedirects){let bulkMatch=resolveBulkRedirect(this.bulkRedirects,req.url||"/",typeof req.headers.host=="string"?req.headers.host:void 0);if(bulkMatch){debug(`Bulk redirect ${bulkMatch.statusCode}: ${req.url} -> ${bulkMatch.location}`),await this.sendRedirect(req,res,requestId,bulkMatch.location,bulkMatch.statusCode);return}}if(callLevel===0&&this.orchestrator){let pathname=parsed.pathname||"/",service=this.orchestrator.getServiceForRoute(pathname);if(service){debug(`Found service: ${service.name}`);let upstream=`http://${service.host}:${service.port}`;debug(`Proxying to service "${service.name}": ${upstream}`);let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.setResponseHeaders(res,requestId),proxyPass(req,res,upstream,this,requestId,!1)}}callLevel===0&&await this.updateBuildMatches(vercelConfig),this.blockingBuildsPromise&&(debug("Waiting for builds to complete before handling request"),await this.blockingBuildsPromise);let getReqUrl=rr=>{if(rr.dest){if(rr.query){let destParsed=url3.parse(rr.dest),destQuery=parseQueryString(destParsed.search);return Object.assign(destQuery,rr.query),destParsed.search=formatQueryString(destQuery),url3.format(destParsed)}return rr.dest}return req.url},handleMap=getRoutesTypes(routes),missRoutes=handleMap.get("miss")||[],hitRoutes=handleMap.get("hit")||[],errorRoutes=handleMap.get("error")||[],filesystemRoutes=handleMap.get("filesystem")||[],phases=[null,"filesystem"],routeResult=null,match=null,statusCode,prevUrl=req.url,prevHeaders={},requestTransforms=[],responseTransforms,middlewares=[...this.buildMatches.values()].filter(m=>m.config?.middleware===!0);for(let middleware of middlewares){let startMiddlewareResult,middlewarePid,{envConfigs,files,devCacheDir,cwd:workPath}=this;try{let{builder:builder2}=middleware.builderWithPkg;if(typeof builder2.startDevServer=="function"&&(startMiddlewareResult=await builder2.startDevServer({files,entrypoint:middleware.entrypoint,workPath,repoRootPath:this.repoRoot,config:{projectSettings:this.projectSettings,...middleware.config},meta:{isDev:!0,...this.getDevResourceMeta(),devCacheDir,requestUrl:req.url,env:this.getBuilderDevEnv(middleware,envConfigs.runEnv),buildEnv:{...envConfigs.buildEnv}}})),startMiddlewareResult){let{port,pid,shutdown}=startMiddlewareResult;middlewarePid=pid,this.shutdownCallbacks.set(pid,shutdown),debug(`Invoking middleware "${middleware.src}" (port=${port})`);let middlewareReqHeaders=nodeHeadersToFetchHeaders(req.headers),proxyHeaders=this.getProxyHeaders(req,requestId,!0);for(let[name,value]of nodeHeadersToFetchHeaders(proxyHeaders))middlewareReqHeaders.set(name,value);let middlewareReqPath=url3.parse(req.url||"/").path||"/",middlewareRes=await directFetch(`http://127.0.0.1:${port}${middlewareReqPath}`,{headers:middlewareReqHeaders,method:req.method,redirect:"manual"}),middlewareBody=Buffer.from(await middlewareRes.arrayBuffer());if(middlewareRes.status===500&&middlewareBody.byteLength===0){await this.sendError(req,res,requestId,"EDGE_FUNCTION_INVOCATION_FAILED",500);return}res.statusCode=middlewareRes.status;let rewritePath="",contentType2="",shouldContinue=!1,skipMiddlewareHeaders=new Set(["date","connection","content-length","transfer-encoding"]),middlewareHeaders=applyOverriddenHeaders(req.headers,middlewareRes.headers);for(let[name,value]of middlewareHeaders)name==="x-middleware-next"?shouldContinue=value==="1":name==="x-middleware-rewrite"?(rewritePath=value,shouldContinue=!0):name==="content-type"?contentType2=value:skipMiddlewareHeaders.has(name)||(applyChainResponseHeader(res,name,value),req.headers[name]=value);if(!shouldContinue){this.setResponseHeaders(res,requestId),middlewareBody.length>0?(res.setHeader("content-length",middlewareBody.length),contentType2&&res.setHeader("content-type",contentType2),res.end(middlewareBody)):res.end();return}if(rewritePath){debug(`Detected rewrite path from middleware: "${rewritePath}"`),prevUrl=rewritePath;let beforeRewriteUrl=req.url||"/";if(isURL(rewritePath)){let rewriteUrlParsed=new URL2(rewritePath);if(this.address.origin===rewriteUrlParsed.origin)req.url=rewritePath.slice(rewriteUrlParsed.origin.length)||"/",prevUrl=req.url;else{debug(`ProxyPass: ${rewritePath}`),this.setResponseHeaders(res,requestId),proxyPass(req,res,rewritePath,this,requestId);return}}else{let rewriteUrlParsed=url3.parse(beforeRewriteUrl);rewriteUrlParsed.search=url3.parse(rewritePath).search,req.url=url3.format(rewriteUrlParsed)}debug(`Rewrote incoming HTTP URL from "${beforeRewriteUrl}" to "${req.url}"`)}}}catch(err){(0,import_error_utils.isSpawnError)(err)&&err.code==="ENOENT"&&(err.message=`Command not found: ${import_chalk2.default.cyan(err.path,...err.spawnargs)}
|
|
54
54
|
Please ensure that ${cmd(err.path)} is properly installed`,err.link="https://vercel.link/command-not-found"),output_manager_default.prettyError(err),await this.sendError(req,res,requestId,"MIDDLEWARE_INVOCATION_FAILED",500);return}finally{middlewarePid&&this.killBuilderDevServer(middlewarePid)}}for(let phase of phases){statusCode=void 0;let phaseRoutes=handleMap.get(phase)||[];if(routeResult=await devRouter(prevUrl,req.method,phaseRoutes,this,vercelConfig,prevHeaders,missRoutes,phase),routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms),routeResult.continue&&(routeResult.dest&&(prevUrl=getReqUrl(routeResult)),routeResult.headers&&(prevHeaders=routeResult.headers)),callLevel===0&&this.orchestrator&&!routeResult.continue&&isServiceDestination(routeResult.matched_route))return this.delegateToService(req,res,requestId,routeResult.matched_route,vercelConfig,requestTransforms,responseTransforms);if(routeResult.isDestUrl){let destParsed=url3.parse(routeResult.dest),destQuery=parseQueryString(destParsed.search);Object.assign(destQuery,routeResult.query),destParsed.search=formatQueryString(destQuery);let destUrl=url3.format(destParsed);return this.prepareTransforms(req,requestTransforms,responseTransforms),debug(`ProxyPass: ${destUrl}`),this.setResponseHeaders(res,requestId),proxyPass(req,res,destUrl,this,requestId)}if(match=await findBuildMatch(this.buildMatches,this.files,routeResult.dest,this,vercelConfig),await this.exitWithStatus(match,routeResult,phase,req,res,requestId,responseTransforms))return;if(!match&&missRoutes.length>0){if(routeResult=await devRouter(getReqUrl(routeResult),req.method,missRoutes,this,vercelConfig,routeResult.headers,[],"miss"),routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms),match=await findBuildMatch(this.buildMatches,this.files,routeResult.dest,this,vercelConfig),await this.exitWithStatus(match,routeResult,phase,req,res,requestId,responseTransforms))return}else if(match&&hitRoutes.length>0){let prevStatus=routeResult.status;routeResult=await devRouter(getReqUrl(routeResult),req.method,hitRoutes,this,vercelConfig,routeResult.headers,[],"hit"),routeResult.status=prevStatus,routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms)}if(statusCode=routeResult.status,match||phase===null&&filesystemRoutes.length===0)break}if(!match&&routeResult&&errorRoutes.length>0){let routeResultForError=await devRouter(getReqUrl(routeResult),req.method,errorRoutes,this,vercelConfig,routeResult.headers,[],"error"),{matched_route}=routeResultForError,matchForError=await findBuildMatch(this.buildMatches,this.files,routeResultForError.dest,this,vercelConfig);if(matchForError)debug("Route match detected in error phase, breaking loop"),routeResult=routeResultForError,statusCode=routeResultForError.status,match=matchForError,routeResult.requestTransforms&&requestTransforms.push(...routeResult.requestTransforms),routeResult.responseTransforms&&(responseTransforms=routeResult.responseTransforms);else if(matched_route&&matched_route.src&&!matched_route.dest&&(debug("Route without `dest` detected in error phase, attempting to exit early"),await this.exitWithStatus(matchForError,routeResultForError,"error",req,res,requestId,responseTransforms)))return}if(!routeResult)throw dev.DEV_INTERNAL_NO_ROUTE_RESULT();let{dest,query,headers}=routeResult;for(let[name,value]of Object.entries(headers))res.setHeader(name,value);statusCode&&Object.defineProperty(res,"statusCode",{get(){return statusCode},set(_){}});let requestPath=dest.replace(/^\//,"");if(!match){if(this.devProcessOrigin){let upstream=this.devProcessOrigin;debug(`Proxying to frontend dev server: ${upstream}`);let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;this.setResponseHeaders(res,requestId);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);return origUrl.pathname=dest,Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format(origUrl),this.prepareTransforms(req,requestTransforms,responseTransforms),proxyPass(req,res,upstream,this,requestId,!1)}(statusCode===404&&routeResult.phase==="miss"||!this.renderDirectoryListing(req,res,requestPath,requestId))&&await this.send404(req,res,requestId);return}let buildRequestPath=match.buildResults.has(null)?null:requestPath,buildResult=match.buildResults.get(buildRequestPath);if(buildResult&&Array.isArray(buildResult.routes)&&buildResult.routes.length>0){let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);origUrl.pathname=dest,Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery);let newUrl=url3.format(origUrl);debug(`Checking build result's ${buildResult.routes.length} \`routes\` to match ${newUrl}`);let matchedRoute=await devRouter(newUrl,req.method,buildResult.routes,this,vercelConfig);if(matchedRoute.found&&callLevel===0){debug(`Found matching route ${matchedRoute.dest} for ${newUrl}`),req.url=newUrl,await this.serveProjectAsNowV2(req,res,requestId,vercelConfig,buildResult.routes,callLevel+1);return}}let{builder,pkg:builderPkg}=match.builderWithPkg;if(typeof builder.startDevServer=="function"){let devServerResult=null;try{devServerResult=await this.startBuildMatchDevServer(match,requestPath)}catch(err){(0,import_error_utils.isSpawnError)(err)&&err.code==="ENOENT"&&(err.message=`Command not found: ${import_chalk2.default.cyan(err.path,...err.spawnargs)}
|
|
55
|
-
Please ensure that ${cmd(err.path)} is properly installed`,err.link="https://vercel.link/command-not-found"),output_manager_default.prettyError(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}if(devServerResult){requestId=generateRequestId(this.podId,!0);let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown),persistent||res.once("close",()=>{this.killBuilderDevServer(pid)}),debug(`Proxying to "${builderPkg.name}" dev server (port=${port}, pid=${pid})`);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search});let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,`http://127.0.0.1:${port}`,this,requestId,!1)}else debug(`Skipping \`startDevServer()\` for ${match.entrypoint}`)}let foundAsset=findAsset(match,requestPath,vercelConfig);if(!foundAsset&&callLevel===0&&(await this.triggerBuild(match,buildRequestPath,req,vercelConfig),foundAsset=findAsset(match,requestPath,vercelConfig)),this.devProcessOrigin&&(!foundAsset||foundAsset&&foundAsset.asset.type!=="Lambda")){debug("Proxying to frontend dev server");let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,this.devProcessOrigin,this,requestId,!1)}if(!foundAsset){await this.send404(req,res,requestId);return}let{asset,assetKey}=foundAsset;switch(debug(`Serving asset: [${asset.type}] ${assetKey} ${asset.contentType||""}`),asset.type){case"FileFsRef":this.setResponseHeaders(res,requestId);let staticResHeaders={};applyResponseTransforms(staticResHeaders,responseTransforms??[]);for(let[name,value]of Object.entries(staticResHeaders))value!==void 0&&res.setHeader(name,value);return req.url=`/${basename(asset.fsPath)}`,serveStaticFile(req,res,dirname3(asset.fsPath),{headers:[{source:"**/*",headers:[{key:"Content-Type",value:asset.contentType||getMimeType(assetKey)}]}]});case"FileBlob":let headers2={"Content-Length":asset.data.length,"Content-Type":asset.contentType||getMimeType(assetKey)};applyResponseTransforms(headers2,responseTransforms??[]),this.setResponseHeaders(res,requestId,headers2),res.end(asset.data);return;case"Lambda":if(!asset.fn){await this.sendError(req,res,requestId,"INTERNAL_LAMBDA_NOT_FOUND");return}requestId=generateRequestId(this.podId,!0);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search}),applyRequestTransforms(req,requestTransforms);let path6=req.url||"/",body=await(0,import_raw_body2.default)(req);debug(`Invoking lambda: "${assetKey}" with ${path6}`);let result;try{result=await this.invokeBuiltLambda(asset,req,requestId,body)}catch(err){console.error(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}statusCode||(res.statusCode=result.statusCode);let lambdaHeaders=result.headers??{};applyResponseTransforms(lambdaHeaders,responseTransforms??[]),this.setResponseHeaders(res,requestId,lambdaHeaders);let resBody;return result.encoding==="base64"&&typeof result.body=="string"?resBody=Buffer.from(result.body,"base64"):resBody=result.body,res.end(resBody);default:await this.sendError(req,res,requestId,"UNKNOWN_ASSET_TYPE")}};this.cwd=cwd,this.repoRoot=options.repoRoot??cwd,this.envConfigs={buildEnv:{},runEnv:{},allEnv:{}},this.envValues=options.envValues||{},this.projectId=options.projectId,this.orgId=options.orgId,this.queuePort=options.queuePort,this.runtimeCachePort=options.runtimeCachePort,this.schedulesPort=options.schedulesPort,this.scheduleBroker=new import_local_schedules2.ScheduleBroker({ownerId:this.orgId??"team_local",projectId:this.projectId??"prj_local",trackId:"development",dispatch:invocation=>this.dispatchSchedule(invocation),onError:(err,invocation)=>{try{output_manager_default.error(`Failed to dispatch schedule "${invocation.schedule.name}": ${(0,import_error_utils.errorToString)(err)}`)}catch{}}}),this.resourceProxyToken=randomBytes2(32).toString("base64url"),this.reportError=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");return{queues:{direct:this.queueOrigin,proxy:`${this.address.origin}${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`},runtimeCache:{direct:`${this.runtimeCacheOrigin}${DEV_RUNTIME_CACHE_API_PREFIX}`,proxy:`${this.address.origin}${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}${DEV_RUNTIME_CACHE_API_PREFIX}`},...this.schedulesOrigin?{schedules:{direct:this.schedulesOrigin,proxy:`${this.address.origin}${DEV_SCHEDULES_PROXY_PREFIX}/${this.resourceProxyToken}`}}:{}}}getDevResourceMeta(){return{devResourceEndpoints:this.resourceEndpoints}}handleResourceServerRequest(req,res,origin,handler){if(!origin||!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}if(!isValidDevResourceHost(origin,req.headers.host)){res.writeHead(403),res.end("Forbidden");return}let pathname=new URL2(req.url||"/","http://127.0.0.1").pathname;handler(req,res,pathname).catch(err=>{output_manager_default.debug(`Local resource request failed for ${req.url||"/"}: ${(0,import_error_utils.errorToString)(err)}`),res.headersSent||res.writeHead(500),res.end("Internal Server Error")})}isAuthorizedResourceRequest(req,token){let authorization=req.headers.authorization;if(typeof authorization!="string")return!1;let encoder=new TextEncoder,actual=encoder.encode(authorization),expected=encoder.encode(`Bearer ${token}`);return actual.length===expected.length&&timingSafeEqual(actual,expected)}getBuilderDevEnv(match,env){let result={...env,...getDevSchedulesEnv(this.schedulesOrigin)};if(match.builderWithPkg.pkg.name!=="@vercel/container")return result;let endpoints=this.resourceEndpoints;return Object.assign(result,getDevSchedulesEnv(endpoints.schedules?.proxy,!0)),result.VERCEL_QUEUE_BASE_URL===endpoints.queues.direct&&Object.assign(result,getDevQueueEnv(endpoints.queues.proxy,result.VERCEL_HAS_WORKER_SERVICES!==void 0)),result.RUNTIME_CACHE_ENDPOINT===endpoints.runtimeCache.direct&&Object.assign(result,getDevRuntimeCacheEnv(endpoints.runtimeCache.proxy,"")),result}getSidecarDevMeta(match){let serviceCount=(this.sidecars??[]).filter(sidecar=>sidecar.builder.use!==match.use?!1:!sidecar.workspace||sidecar.workspace===".").length;return serviceCount>0?{serviceCount}:{}}async setupBuilderDevSidecars(){if(this.shouldUseServicesOrchestrator())return;let sidecars=this.sidecars??[];if(sidecars.length===0)return;Object.assign(this.envConfigs.runEnv,this.getDevQueueEnv());let services=sidecars.map(toOrchestratorService),orchestrator=new ServicesOrchestrator({services,cwd:this.cwd,repoRoot:this.repoRoot,env:this.envConfigs.allEnv,proxyOrigin:this.address.origin,resourceEndpoints:this.resourceEndpoints,useImplicitEnvInjection:!1,preferServiceBuilder:!0,onQueueSubscriptions:(serviceName,subscriptions)=>this.queueBroker?.updateServiceSubscriptions(serviceName,subscriptions)});this.sidecarOrchestrator=orchestrator,this.queueBroker?.registerServices(services);try{await orchestrator.startAll()}catch(err){throw await orchestrator.stopAll(),this.sidecarOrchestrator=void 0,this.sidecars=[],err}output_manager_default.log(`Started ${sidecars.length} development ${(0,import_pluralize2.default)("sidecar",sidecars.length)}`)}async exit(code=1){await this.stop(code),process.exit(code)}enqueueFsEvent(type,path6){this.bulkRedirectsResolvedPath&&(path6===this.bulkRedirectsResolvedPath||path6.startsWith(this.bulkRedirectsResolvedPath+sep2))&&(this.bulkRedirectsDirty=!0),this.watchAggregationEvents.push({type,path:path6}),this.watchAggregationId===null&&(this.watchAggregationId=setTimeout(()=>{let events=this.watchAggregationEvents.slice();this.watchAggregationEvents.length=0,this.watchAggregationId=null,this.handleFilesystemEvents(events).catch(err=>{output_manager_default.prettyError(err),(0,import_error_utils.isError)(err)&&typeof err.stack=="string"&&output_manager_default.debug(err.stack)})},this.watchAggregationTimeout))}async handleFilesystemEvents(events){if(this.stopping)return;output_manager_default.debug(`Filesystem watcher notified of ${events.length} events`);let filesChanged=new Set,filesRemoved=new Set,distPaths=[];for(let buildMatch of this.buildMatches.values())for(let buildResult of buildMatch.buildResults.values())buildResult.distPath&&distPaths.push(buildResult.distPath);if(events=events.filter(event=>distPaths.every(distPath=>!event.path.startsWith(distPath))),events.length!==0){this.functionReconciliations++;try{this.configGeneration++,this.functionDiscovery=void 0;for(let event of events)event.type==="add"?await this.handleFileCreated(event.path,filesChanged,filesRemoved):event.type==="unlink"?this.handleFileDeleted(event.path,filesChanged,filesRemoved):event.type==="change"&&await this.handleFileModified(event.path,filesChanged,filesRemoved);let vercelConfig=await this.getVercelConfig();if(this.stopping)return;await this.updateBuildMatches(vercelConfig);let filesChangedArray=[...filesChanged],filesRemovedArray=[...filesRemoved],needsRebuild=new Map;for(let match of this.buildMatches.values()){this.canonicalizeFunctionBuild(match);for(let[requestPath,result]of match.buildResults)if(!needsRebuild.has(result)&&Array.isArray(result.watch)){for(let pattern of result.watch)if(minimatches(filesChangedArray,pattern)||minimatches(filesRemovedArray,pattern)){needsRebuild.set(result,[requestPath,match]);break}}}if(needsRebuild.size>0){output_manager_default.debug(`Triggering ${needsRebuild.size} rebuilds`),filesChangedArray.length>0&&output_manager_default.debug(`Files changed: ${filesChangedArray.join(", ")}`),filesRemovedArray.length>0&&output_manager_default.debug(`Files removed: ${filesRemovedArray.join(", ")}`);for(let[result,[requestPath,match]]of needsRebuild)requestPath===null||await shouldServe(match,this.files,requestPath,this,vercelConfig)?this.triggerBuild(match,requestPath,null,vercelConfig,result,filesChangedArray,filesRemovedArray).catch(err=>{output_manager_default.warn(`An error occurred while rebuilding \`${match.src}\`:`),console.error(err.stack)}):output_manager_default.debug(`Not rebuilding because \`shouldServe()\` returned \`false\` for "${match.use}" request path "${requestPath}"`)}}finally{this.functionReconciliations--}}}async handleFileCreated(fsPath,changed,removed){let name=relative2(this.cwd,fsPath);try{await this.getVercelConfig(),this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath});let extensionless=this.getExtensionlessFile(name);extensionless&&(this.files[extensionless]=await import_build_utils9.FileFsRef.fromFsPath({fsPath})),fileChanged(name,changed,removed),output_manager_default.debug(`File created: ${name}`)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File created, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}handleFileDeleted(fsPath,changed,removed){let name=relative2(this.cwd,fsPath);output_manager_default.debug(`File deleted: ${name}`),fileRemoved(name,this.files,changed,removed);let extensionless=this.getExtensionlessFile(name);extensionless&&(output_manager_default.debug(`File deleted: ${extensionless}`),fileRemoved(extensionless,this.files,changed,removed))}async handleFileModified(fsPath,changed,removed){let name=relative2(this.cwd,fsPath);try{this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath}),fileChanged(name,changed,removed),output_manager_default.debug(`File modified: ${name}`)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File modified, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}async updateBuildMatches(vercelConfig,isInitial=!1){let fileList=this.resolveBuildFiles(this.files),matches=await getBuildMatches(vercelConfig,this.cwd,this,fileList),sources=matches.map(m=>m.src);isInitial&&fileList.length===0&&output_manager_default.warn("There are no files inside your deployment.");let ops=[];for(let src of this.buildMatches.keys())if(!sources.includes(src)){output_manager_default.debug(`Removing build match for "${src}"`);let match=this.buildMatches.get(src);match&&ops.push(shutdownBuilder(match)),this.buildMatches.delete(src)}await Promise.all(ops);let blockingBuilds=[];for(let match of matches){let currentMatch=this.buildMatches.get(match.src);if(!buildMatchEquals(currentMatch,match)&&(output_manager_default.debug(`Adding build match for "${match.src}" with "${match.use}"`),this.buildMatches.set(match.src,match),!isInitial&&needsBlockingBuild(match))){let buildPromise=executeBuild(vercelConfig,this,this.files,match,null,!1);blockingBuilds.push(buildPromise)}}blockingBuilds.length>0&&(output_manager_default.debug(`Waiting for ${blockingBuilds.length} "blocking builds"`),this.blockingBuildsPromise=Promise.all(blockingBuilds).then(()=>{output_manager_default.debug('Cleaning up "blockingBuildsPromise" after successful resolve'),this.blockingBuildsPromise=null}).catch(err=>{output_manager_default.debug(`Cleaning up "blockingBuildsPromise" after error: ${err}`),this.blockingBuildsPromise=null,err&&output_manager_default.prettyError(err)})),this.buildMatches=new Map([...this.buildMatches.entries()].sort((matchA,matchB)=>sortBuilders(matchA[1],matchB[1])))}async getLocalEnv(fileName,base){let filePath=join4(this.cwd,fileName),env={};try{let dotenv=await import_fs_extra.default.readFile(filePath,"utf8");output_manager_default.debug(`Using local env: ${filePath}`),env=(0,import_dotenv.parse)(dotenv),env=this.injectSystemValuesInDotenv(env)}catch(err){if(!(0,import_error_utils.isErrnoException)(err)||err.code!=="ENOENT")throw err}try{return{...this.validateEnvConfig(fileName,base||{},env)}}catch(err){if(err instanceof MissingDotenvVarsError)this.reportError(err),await this.exit();else throw err}return{}}getVercelConfig(){if(this.getVercelConfigPromise)return this.getVercelConfigPromise;this.getVercelConfigPromise=(async()=>{for(;;){let generation=this.configGeneration;try{let config=await this._getVercelConfig();if(this.stopping||generation===this.configGeneration)return config}catch(err){if(this.stopping||generation===this.configGeneration)throw err}this.functionDiscovery=void 0}})();let clear=this.clearVercelConfigPromise;return this.getVercelConfigPromise.then(clear,clear),this.getVercelConfigPromise}get devCommand(){return this.getDevCommand(this.projectSettings)}getDevCommand(projectSettings){if(projectSettings?.devCommand)return projectSettings.devCommand;if(projectSettings?.framework){let frameworkSlug=projectSettings.framework,framework=import_frameworks3.frameworkList.find(f=>f.slug===frameworkSlug);if(framework){let defaults=framework.settings.devCommand.value;if(defaults)return defaults}if((0,import_build_utils9.shouldUseExperimentalBackends)(frameworkSlug))return"npx @vercel/cervel dev"}}getFunctionDiscovery(options){let key=JSON.stringify(options);if(!this.functionDiscovery||this.functionDiscovery.key!==key){let promise=collectDevFunctions(options);this.functionDiscovery={key,promise},promise.catch(()=>{this.functionDiscovery?.promise===promise&&(this.functionDiscovery=void 0)})}return this.functionDiscovery.promise}getDevFunction(outputPath){return this.functionRegistry.functions.get(outputPath)}getDevSchedules(){return this.functionRegistry.schedules}async dispatchSchedule({delivery,signal}){if(signal.throwIfAborted(),this.stopping)throw new Error("Local Schedules is stopping");if(delivery.type==="queue"){if(!this.queueBroker)throw new Error("Local Queue broker is not ready");this.queueBroker.enqueue(delivery.topic,Buffer.from(JSON.stringify(delivery.message)),"application/json");return}if(delivery.type==="path"){if(!this.devProcessOrigin)throw new Error(`Schedule path "${delivery.path}" is not ready because the dev server is unavailable`);signal.throwIfAborted();let response=await directFetch(`${this.devProcessOrigin}${delivery.path}`,{method:delivery.requestMethod,signal});if(!response.ok)throw new Error(`Schedule path "${delivery.path}" returned HTTP ${response.status}`);return}let invoke=this.resolveDevFunction(delivery.function);if(!invoke)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);signal.throwIfAborted();let onAbort=()=>{},aborted=new Promise((_,reject)=>{onAbort=()=>reject(signal.reason),signal.addEventListener("abort",onAbort,{once:!0})});try{let result=await Promise.race([aborted,invoke({method:"POST",headers:delivery.headers,body:Buffer.alloc(0),signal})]);if(!result)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);if(!result.ok)throw new Error(`Schedule function "${delivery.function}" returned HTTP ${result.status}`)}finally{signal.removeEventListener("abort",onAbort)}}resolveDevFunction(outputPath){let fn2=this.getDevFunction(outputPath);if(!fn2||this.stopping)return null;if(fn2.invocation.type==="http"){if(!this.devProcessOrigin)return null}else if(!this.functionDispatchReady||this.functionReconciliations>0||!this.getDevFunctionMatch(fn2))return null;return request=>this.invokeDevFunction(outputPath,request)}getDevFunctionMatch(fn2){if(fn2.invocation.type!=="entrypoint"||fn2.scope.target!=="builder")return;let{entrypoint}=fn2.invocation;return[...this.buildMatches.values()].find(match=>match.entrypoint===entrypoint&&match.use===fn2.scope.build.use&&(0,import_fast_deep_equal.default)(match.config??{},fn2.scope.build.config??{}))}canonicalizeFunctionBuild(match){if(![...this.functionRegistry.functions.values()].some(fn2=>this.getDevFunctionMatch(fn2)===match))return!1;if(match.buildResults.size&&!(match.buildResults.size===1&&match.buildResults.has(null))){let results=[...match.buildResults.values()],result=results[results.length-1];result.watch=[...new Set(results.flatMap(result2=>result2.watch))],match.buildResults.clear(),match.buildResults.set(null,result)}return!0}async invokeDevFunction(outputPath,request){request.signal?.throwIfAborted();let fn2=this.getDevFunction(outputPath);if(!fn2||!this.resolveDevFunction(outputPath))return null;let generation=this.configGeneration,isCurrent=()=>!this.stopping&&generation===this.configGeneration&&this.getDevFunction(outputPath)===fn2;if(fn2.invocation.type==="http"){let response=await directFetch(`${this.devProcessOrigin}${fn2.invocation.pathname}`,{...request,redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}let match=this.getDevFunctionMatch(fn2),config=this.functionConfig,req=new http.IncomingMessage(new Socket);req.method=request.method,req.url=`/${outputPath}`,req.headers={host:this.address.host,...request.headers};let requestId=generateRequestId(this.podId,!0),currentMatch=()=>!request.signal?.aborted&&isCurrent()&&this.getDevFunctionMatch(fn2)===match,devServerResult=await this.startBuildMatchDevServer(match,outputPath);if(devServerResult){let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown);try{if(!currentMatch())return null;let response=await directFetch(`http://127.0.0.1:${port}/${outputPath}`,{...request,headers:nodeHeadersToFetchHeaders({...req.headers,...this.getProxyHeaders(req,requestId,!0)}),redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}finally{let current=this.getDevFunction(outputPath);(this.stopping||!persistent||!current||this.getDevFunctionMatch(current)!==match)&&this.shutdownCallbacks.has(pid)&&await this.killBuilderDevServer(pid)}}if(!currentMatch())return null;let{entrypoint}=fn2.invocation,getAsset=()=>match.buildOutput[(match.buildResultVersion??match.builderWithPkg.builder.version)===2?outputPath:entrypoint];this.canonicalizeFunctionBuild(match);let asset=getAsset();if((!asset||this.inProgressBuilds.get(match)?.size)&&(await this.triggerBuild(match,null,null,config),asset=getAsset()),!currentMatch())return null;if(!asset||asset.type!=="Lambda"||!asset.fn)return{ok:!1,status:404};let result=await this.invokeBuiltLambda(asset,req,requestId,request.body);return{ok:result.statusCode>=200&&result.statusCode<300,status:result.statusCode}}async startBuildMatchDevServer(match,requestPath){let{builder}=match.builderWithPkg;if(!builder.startDevServer)return null;let{envConfigs,files,devCacheDir,cwd:workPath}=this;return builder.startDevServer({files,entrypoint:match.entrypoint,workPath,config:match.config||{},repoRootPath:this.repoRoot,meta:{isDev:!0,...this.getDevResourceMeta(),requestPath,devCacheDir,...this.getSidecarDevMeta(match),env:this.getBuilderDevEnv(match,{...envConfigs.runEnv,VERCEL_DEBUG_PREFIX:output_manager_default.debugEnabled?"[builder]":void 0}),buildEnv:{...envConfigs.buildEnv}}})}invokeBuiltLambda(asset,req,requestId,body){let payload={method:req.method||"GET",host:req.headers.host,path:req.url||"/",headers:{...req.headers,...this.getProxyHeaders(req,requestId,!0)},encoding:"base64",body:body.toString("base64")};return asset.fn({Action:"Invoke",body:JSON.stringify(payload)})}async _getVercelConfig(){let generation=this.configGeneration,{compileVercelConfig}=await import("../../chunks/compile-vercel-config-KWSIFONF.js"),compiled=await compileVercelConfig(this.cwd),configPath=getLocalPathConfig(this.cwd,!!compiled.sourceFile),[pkg=null,vercelConfig={version:2,[import_client.fileNameSymbol]:"vercel.json"}]=await Promise.all([this.readJsonFile("package.json"),this.readJsonFile(configPath,!0)]);await this.validateVercelConfig(vercelConfig);let functionConfig=structuredClone(vercelConfig),sourceFiles;for(let[name,service]of Object.entries(this.queueBroker?vercelConfig.services??vercelConfig.experimentalServicesV2??{}:{}))if(Object.values(service.functions??{}).some(fn2=>fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta")))throw dev.DEV_QUEUE_FUNCTION_UNSUPPORTED({sourceFile:`services.${name}.functions`,reason:"service-hosted function queue triggers are not supported locally yet"});let nextProjectSettings={...this.originalProjectSettings,...pickOverrides(vercelConfig)},{error:routeError,routes:maybeRoutes}=(0,import_routing_utils3.getTransformedRoutes)(vercelConfig);routeError&&(this.reportError(routeError),await this.exit()),vercelConfig.routes=maybeRoutes||[];let hasServices=(this.services?.length??0)>0,hasResolvedServices=!!this.services&&this.services.length>0,{schedules}=functionConfig,scheduleEntrypointPlan;if(!hasResolvedServices&&schedules?.some(import_schedule_entrypoint.hasScheduleEntrypointTarget)&&(sourceFiles=(await staticFiles(this.cwd,{})).map(f=>relative2(this.cwd,f)),scheduleEntrypointPlan=(0,import_schedule_entrypoint.planScheduleEntrypoints)({schedules,files:sourceFiles,framework:nextProjectSettings.framework,functions:functionConfig.functions})),!vercelConfig.experimentalServices&&!hasResolvedServices&&(!vercelConfig.builds||vercelConfig.builds.length===0)){let{projectSettings,cleanUrls,trailingSlash}=vercelConfig,files=sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative2(this.cwd,f));sourceFiles=files;let detectionOptions={tag:"latest",reservedFunctionFiles:scheduleEntrypointPlan?.reservedFunctionFiles,bunVersion:vercelConfig.bunVersion,functions:vercelConfig.functions,projectSettings:projectSettings||nextProjectSettings,featHandleMiss:!0,cleanUrls,trailingSlash,proxy:vercelConfig.proxy,workPath:this.cwd},detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions);for(;detectedBuilders.errors?.length===1&&detectedBuilders.errors[0].code==="unused_function";){let error2=detectedBuilders.errors[0],unmatchedTrigger=Object.entries(detectionOptions.functions??{}).find(([pattern,fn2])=>error2.message.startsWith(`The pattern "${pattern}" defined in \`functions\` `)&&fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta"||trigger.type==="schedule/v1beta"));if(!unmatchedTrigger)break;detectionOptions.functions={...detectionOptions.functions},delete detectionOptions.functions[unmatchedTrigger[0]],detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions)}let{builders,warnings,errors,defaultRoutes,redirectRoutes,rewriteRoutes,errorRoutes}=detectedBuilders,hostRewriteRoutes=detectedBuilders.hostRewriteRoutes;if(errors){if(this.functionConfig)throw errors[0];this.reportError(errors[0]),await this.exit()}if(warnings?.length>0&&warnings.forEach(warning=>output_manager_default.warn(warning.message,null,warning.link,warning.action)),builders){let buildpackRuntime=builders.map(getBuildpackRuntime).find(runtime=>runtime!==void 0);if(buildpackRuntime)throw buildpackDevUnsupportedError(buildpackRuntime);vercelConfig.builds=vercelConfig.builds||[],vercelConfig.builds.push(...builders),delete vercelConfig.functions}let serviceRewrites=detectedBuilders.serviceRewrites,serviceRewriteRoutes=serviceRewrites&&serviceRewrites.length>0?(0,import_routing_utils3.convertRewrites)(serviceRewrites):null,routes=[];routes.push(...redirectRoutes||[]),routes=(0,import_routing_utils3.appendRoutesToPhase)({routes,newRoutes:hostRewriteRoutes??null,phase:null}),routes.push(...(0,import_routing_utils3.appendRoutesToPhase)({routes:vercelConfig.routes,newRoutes:[...rewriteRoutes||[],...serviceRewriteRoutes||[]],phase:"filesystem"})),routes=(0,import_routing_utils3.appendRoutesToPhase)({routes,newRoutes:errorRoutes,phase:"error"}),routes.push(...defaultRoutes||[]),vercelConfig.routes=routes}else if(hasResolvedServices&&vercelConfig.proxy){let{entrypoint}=vercelConfig.proxy;await import_fs_extra.default.pathExists(join4(this.cwd,entrypoint))||(output_manager_default.error(`The proxy entrypoint \`${entrypoint}\` does not exist. Set \`proxy.entrypoint\` to an existing \`.js\` or \`.ts\` file.`),await this.exit()),vercelConfig.builds=vercelConfig.builds||[],vercelConfig.builds.push((0,import_fs_detectors2.getProxyBuilder)(vercelConfig.proxy,"latest",vercelConfig.functions))}if(this.sidecars===void 0){let services=(this.services??[]).filter(import_build_utils9.isExperimentalServiceV2);this.sidecars=await collectBuilderDevSidecars({builds:this.shouldUseServicesOrchestrator()?services.map(service=>service.builder):vercelConfig.builds??[],workPath:this.cwd,services})}scheduleEntrypointPlan&&(vercelConfig.builds??=[{src:"**",use:"@vercel/static"}],(0,import_schedule_entrypoint.assertNoScheduleEntrypointSourceConflict)(vercelConfig.builds,scheduleEntrypointPlan),vercelConfig.builds.push(...scheduleEntrypointPlan.builds));let functionBuilds=[...vercelConfig.builds??[]];Array.isArray(vercelConfig.builds)&&((this.getDevCommand(nextProjectSettings)||hasServices)&&(vercelConfig.builds=vercelConfig.builds.filter(this.shouldBuildInDev)),vercelConfig.builds.sort(sortBuilders)),vercelConfig.routes=(vercelConfig.routes||[]).filter(route=>"has"in route?(this.vercelConfigWarning||(this.vercelConfigWarning=!0,output_manager_default.warn(`The "has" property in ${vercelConfig[import_client.fileNameSymbol]} will be ignored during development. Deployments will work as expected.`)),!1):!0);let[runEnv,buildEnv]=await Promise.all([this.getLocalEnv(".env",vercelConfig.env),this.getLocalEnv(".env.build",vercelConfig.build?.env)]),allEnv={...buildEnv,...runEnv};if(Object.keys(allEnv).length===0){let envValues={...this.envValues};this.address.host&&(envValues.VERCEL_URL=this.address.host),allEnv={...envValues},runEnv={...envValues},buildEnv={...envValues}}runEnv.NODE_ENV??=process.env.NODE_ENV??"development",allEnv.NODE_ENV??=runEnv.NODE_ENV,runEnv.NOW_REGION="dev1",buildEnv.NOW_REGION="dev1",allEnv.NOW_REGION="dev1",allEnv.VERCEL_ENV="development",allEnv.VERCEL="1",this.projectId&&!process.env.VERCEL_PROJECT_ID&&("VERCEL_PROJECT_ID"in allEnv||(allEnv.VERCEL_PROJECT_ID=this.projectId),"VERCEL_PROJECT_ID"in runEnv||(runEnv.VERCEL_PROJECT_ID=this.projectId)),this.orgId&&!process.env.VERCEL_ORG_ID&&("VERCEL_ORG_ID"in allEnv||(allEnv.VERCEL_ORG_ID=this.orgId),"VERCEL_ORG_ID"in runEnv||(runEnv.VERCEL_ORG_ID=this.orgId)),nextProjectSettings?.autoExposeSystemEnvs&&(runEnv.VERCEL_REGION="dev1"),runEnv.VERCEL_CLI_VERSION=pkg_default.version,Object.assign(runEnv,this.getDevQueueEnv()),Object.assign(runEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(allEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(runEnv,this.getDevRuntimeCacheEnv(runEnv));let hasQueueFunctions=Object.values(functionConfig.functions??{}).some(fn2=>fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta"));if(this.queueBroker&&hasQueueFunctions&&hasResolvedServices)throw dev.DEV_QUEUE_FUNCTION_UNSUPPORTED({sourceFile:"functions",reason:"service-hosted function queue triggers are not supported locally yet"});let registry=await this.getFunctionDiscovery({scopes:(hasResolvedServices?[]:functionBuilds).map(build=>({build,target:vercelConfig.builds?.includes(build)?"builder":"framework"})),workPath:this.cwd,files:(sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative2(this.cwd,f))).sort(),config:functionConfig,env:{...process.env,...allEnv,...this.getDevQueueEnv(),...getDevSchedulesEnv(this.schedulesOrigin),...this.getDevRuntimeCacheEnv(allEnv)}}),subscriptions,staticSchedules,sourceChanged;try{subscriptions=deriveQueueSubscriptions(registry),this.queueBroker?.validateFunctionSubscriptions(subscriptions),staticSchedules=collectStaticSchedules(scheduleEntrypointPlan&&schedules?(0,import_schedule_entrypoint.resolveScheduleEntrypointTargets)(schedules,scheduleEntrypointPlan):functionConfig.schedules,registry),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&this.scheduleBroker.validateStatic(staticSchedules)}catch(err){throw this.functionDiscovery=void 0,err}let{unmatchedPatterns}=registry;if(await this.refreshBulkRedirects(vercelConfig.bulkRedirectsPath),this.devCommandStarts.size&&await Promise.all(this.devCommandStarts),this.stopping||generation!==this.configGeneration)return vercelConfig;let restartForFunctionEnv=!!(this.devCommandEnv&&[...registry.functions.values()].some(fn2=>fn2.invocation.type==="http")&&!(0,import_fast_deep_equal.default)(this.devCommandEnv,allEnv)),previousProcess=this.devProcess,previousOrigin=this.devProcessOrigin,previousCommand=this.currentDevCommand,previousEnv=this.devCommandEnv,previousRuntime={projectSettings:this.projectSettings,allEnv:previousEnv??this.envConfigs.allEnv},restarted,validated=!1;try{if(this.initialDevCommandStarted&&await this.runDevCommand(restartForFunctionEnv,{projectSettings:nextProjectSettings,allEnv},origin=>{restarted={origin}}),this.stopping||generation!==this.configGeneration)return vercelConfig;this.queueBroker?.validateFunctionSubscriptions(subscriptions),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&(this.scheduleBroker.validateStatic(staticSchedules),this.scheduleBroker.reconcileStatic(staticSchedules),this.staticSchedulesSnapshot=structuredClone(staticSchedules)),validated=!0}finally{!this.stopping&&!validated&&(this.devProcess!==previousProcess||this.devProcessOrigin!==previousOrigin||this.currentDevCommand!==previousCommand||this.devCommandEnv!==previousEnv)&&await this.runDevCommand(!0,previousRuntime)}this.projectSettings=nextProjectSettings,this.caseSensitive=hasNewRoutingProperties(vercelConfig),this.apiDir=(0,import_fs_detectors2.detectApiDirectory)(vercelConfig.builds||[]),this.apiExtensions=(0,import_fs_detectors2.detectApiExtensions)(vercelConfig.builds||[]),this.envConfigs={buildEnv,runEnv,allEnv},this.functionRegistry=registry,this.functionConfig=vercelConfig,restarted&&(this.devProcessOrigin=restarted.origin),this.queueBroker?.setFunctionSubscriptions(subscriptions,outputPath=>this.resolveDevFunction(outputPath));for(let pattern of unmatchedPatterns)if(!this.unmatchedQueuePatterns.has(pattern)){let warning=dev.DEV_QUEUE_FUNCTION_UNMATCHED({pattern});output_manager_default.warn(`[${warning.name}] ${warning.message} ${warning.fix}`)}return this.unmatchedQueuePatterns=new Set(unmatchedPatterns),vercelConfig}async refreshBulkRedirects(bulkRedirectsPath){let configPath=bulkRedirectsPath??null;if(configPath===this.bulkRedirectsLastPath&&!this.bulkRedirectsDirty)return;if(this.bulkRedirectsLastPath=configPath,this.bulkRedirectsDirty=!1,this.bulkRedirectsResolvedPath=configPath?resolveBulkRedirectsPath(this.cwd,configPath):null,!configPath){this.bulkRedirects=null,this.bulkRedirectsSignature=null;return}let signature=await getBulkRedirectsSignature(this.cwd,configPath);if(signature!==this.bulkRedirectsSignature){this.bulkRedirectsSignature=signature;try{let result=await loadBulkRedirects(this.cwd,configPath);this.bulkRedirects=result.table;for(let warning of result.warnings)output_manager_default.warn(warning);let count=result.table.size;count>0&&output_manager_default.log(`Loaded ${count} bulk ${(0,import_pluralize2.default)("redirect",count)} from ${configPath}`)}catch(err){this.bulkRedirects=null,output_manager_default.warn(`Failed to load bulk redirects from "${configPath}": ${(0,import_error_utils.errorToString)(err)}`)}}}async readJsonFile(filePath,strict=!1){let rel,abs;isAbsolute3(filePath)?(rel=path4.relative(this.cwd,filePath),abs=filePath):(rel=filePath,abs=join4(this.cwd,filePath)),output_manager_default.debug(`Reading \`${rel}\` file`);try{let raw=await import_fs_extra.default.readFile(abs,"utf8"),parsed=(0,import_json_parse_better_errors.default)(raw);return parsed[import_client.fileNameSymbol]=rel,parsed}catch(err){if(strict&&!((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT"))throw err;if((0,import_error_utils.isError)(err))(0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT"?output_manager_default.debug(`No \`${rel}\` file present`):err.name==="SyntaxError"&&output_manager_default.warn(`There is a syntax error in the \`${rel}\` file: ${err.message}`);else throw err}}async tryValidateOrExit(config,validate){let message2=validate(config);message2&&(output_manager_default.error(message2),await this.exit(1))}async validateVercelConfig(config){if(config.version===1){if(this.functionConfig)throw dev.DEV_UNSUPPORTED_CONFIG_VERSION();this.reportError(dev.DEV_UNSUPPORTED_CONFIG_VERSION()),await this.exit(1);return}let error2=validateConfig(config);if(error2){if(this.functionConfig)throw error2;this.reportError(error2),await this.exit(1)}}validateEnvConfig(type,env={},localEnv={}){let missing=Object.entries(env).filter(([name,value])=>typeof value=="string"&&value.startsWith("@")&&!hasProp(localEnv,name)).map(([name])=>name);if(missing.length>0)throw new MissingDotenvVarsError(type,missing);let merged={...env,...localEnv},hasInvalidName=!1;for(let key of Object.keys(merged))/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)||(output_manager_default.warn(`Ignoring ${type.split(".").slice(1).reverse().join(" ")} var ${JSON.stringify(key)} because name is invalid`),hasInvalidName=!0,delete merged[key]);return hasInvalidName&&output_manager_default.log("The name contains invalid characters. Only letters, digits, and underscores are allowed. Furthermore, the name should not start with a digit"),merged}injectSystemValuesInDotenv(env){for(let name of Object.keys(env))name==="VERCEL_URL"?env.VERCEL_URL=this.address.host:name==="VERCEL_REGION"&&(env.VERCEL_REGION="dev1");return env}resolveBuildFiles(files){return Object.keys(files).filter(this.filter)}isWatcherIgnored(fsPath){let relativePath=relative2(this.cwd,fsPath);return relativePath===""?!1:!this.filter(relativePath)}start(...listenSpec){return this.startPromise||(this.startPromise=this._start(...listenSpec).catch(async err=>{throw await this.stop(),err})),this.startPromise}async _start(...listenSpec){if(this.stopping)return;if(!import_fs_extra.default.existsSync(this.cwd))throw dev.DEV_CWD_NOT_FOUND({cwd:this.cwd});if(!import_fs_extra.default.lstatSync(this.cwd).isDirectory())throw dev.DEV_CWD_NOT_DIRECTORY({cwd:this.cwd});let{ig}=await(0,import_client.getVercelIgnore)(this.cwd);this.filter=ig.createFilter();let address=null;for(;typeof address!="string";){if(this.stopping)return;try{address=(await(this.listenerStartup=(0,import_async_listen.listen)(this.server,...listenSpec))).toString()}catch(err){if((0,import_error_utils.isErrnoException)(err))if(output_manager_default.debug(`Got listen error: ${err.code}`),err.code==="EADDRINUSE")typeof listenSpec[0]=="number"?(output_manager_default.note(`Requested port ${import_chalk2.default.yellow(String(listenSpec[0]))} is already in use`),listenSpec[0]++):(this.reportError(dev.DEV_LISTEN_ADDRESS_IN_USE({address:String(listenSpec[0])})),process.exit(1));else throw err;else throw err}}if(this.stopping)return;this._address=new URL2(replaceLocalhost(address)),this.runtimeCache=new RuntimeCacheStore;let runtimeCacheListener=await(this.listenerStartup=listenOnDevResourcePort(this.runtimeCacheServer,{name:"Runtime Cache",flag:"--runtime-cache-port",defaultPort:DEV_RUNTIME_CACHE_DEFAULT_PORT,port:this.runtimeCachePort,reservedPorts:[this.queuePort,this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT].filter(port=>port!==void 0&&port!==0)}));if(this.stopping)return;this.runtimeCacheOrigin=runtimeCacheListener.origin,runtimeCacheListener.defaultPort!==void 0&&output_manager_default.warn(`Runtime Cache default port ${runtimeCacheListener.defaultPort} is unavailable; listening on ${runtimeCacheListener.port} instead.
|
|
55
|
+
Please ensure that ${cmd(err.path)} is properly installed`,err.link="https://vercel.link/command-not-found"),output_manager_default.prettyError(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}if(devServerResult){requestId=generateRequestId(this.podId,!0);let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown),persistent||res.once("close",()=>{this.killBuilderDevServer(pid)}),debug(`Proxying to "${builderPkg.name}" dev server (port=${port}, pid=${pid})`);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search});let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,`http://127.0.0.1:${port}`,this,requestId,!1)}else debug(`Skipping \`startDevServer()\` for ${match.entrypoint}`)}let foundAsset=findAsset(match,requestPath,vercelConfig);if(!foundAsset&&callLevel===0&&(await this.triggerBuild(match,buildRequestPath,req,vercelConfig),foundAsset=findAsset(match,requestPath,vercelConfig)),this.devProcessOrigin&&(!foundAsset||foundAsset&&foundAsset.asset.type!=="Lambda")){debug("Proxying to frontend dev server");let headers2=this.getProxyHeaders(req,requestId,!1);for(let[name,value]of Object.entries(headers2))req.headers[name]=value;return this.prepareTransforms(req,requestTransforms,responseTransforms),this.setResponseHeaders(res,requestId),proxyPass(req,res,this.devProcessOrigin,this,requestId,!1)}if(!foundAsset){await this.send404(req,res,requestId);return}let{asset,assetKey}=foundAsset;switch(debug(`Serving asset: [${asset.type}] ${assetKey} ${asset.contentType||""}`),asset.type){case"FileFsRef":this.setResponseHeaders(res,requestId);let staticResHeaders={};applyResponseTransforms(staticResHeaders,responseTransforms??[]);for(let[name,value]of Object.entries(staticResHeaders))value!==void 0&&res.setHeader(name,value);return req.url=`/${basename(asset.fsPath)}`,serveStaticFile(req,res,dirname3(asset.fsPath),{headers:[{source:"**/*",headers:[{key:"Content-Type",value:asset.contentType||getMimeType(assetKey)}]}]});case"FileBlob":let headers2={"Content-Length":asset.data.length,"Content-Type":asset.contentType||getMimeType(assetKey)};applyResponseTransforms(headers2,responseTransforms??[]),this.setResponseHeaders(res,requestId,headers2),res.end(asset.data);return;case"Lambda":if(!asset.fn){await this.sendError(req,res,requestId,"INTERNAL_LAMBDA_NOT_FOUND");return}requestId=generateRequestId(this.podId,!0);let origUrl=url3.parse(req.url||"/"),origQuery=parseQueryString(origUrl.search);Object.assign(origQuery,query),origUrl.search=formatQueryString(origQuery),req.url=url3.format({pathname:origUrl.pathname,search:origUrl.search}),applyRequestTransforms(req,requestTransforms);let path6=req.url||"/",body=await(0,import_raw_body2.default)(req);debug(`Invoking lambda: "${assetKey}" with ${path6}`);let result;try{result=await this.invokeBuiltLambda(asset,req,requestId,body)}catch(err){console.error(err),await this.sendError(req,res,requestId,"NO_RESPONSE_FROM_FUNCTION",502);return}statusCode||(res.statusCode=result.statusCode);let lambdaHeaders=result.headers??{};applyResponseTransforms(lambdaHeaders,responseTransforms??[]),this.setResponseHeaders(res,requestId,lambdaHeaders);let resBody;return result.encoding==="base64"&&typeof result.body=="string"?resBody=Buffer.from(result.body,"base64"):resBody=result.body,res.end(resBody);default:await this.sendError(req,res,requestId,"UNKNOWN_ASSET_TYPE")}};this.cwd=cwd,this.repoRoot=options.repoRoot??cwd,this.envConfigs={buildEnv:{},runEnv:{},allEnv:{}},this.envValues=options.envValues||{},this.projectId=options.projectId,this.orgId=options.orgId,this.queuePort=options.queuePort,this.runtimeCachePort=options.runtimeCachePort,this.schedulesPort=options.schedulesPort,this.scheduleBroker=new import_local_schedules2.ScheduleBroker({ownerId:this.orgId??"team_local",projectId:this.projectId??"prj_local",trackId:"development",dispatch:invocation=>this.dispatchSchedule(invocation),onError:(err,invocation)=>{try{output_manager_default.error(`Failed to dispatch schedule "${invocation.schedule.name}": ${(0,import_error_utils.errorToString)(err)}`)}catch{}}}),this.resourceProxyToken=randomBytes2(32).toString("base64url"),this.reportError=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");return{queues:{direct:this.queueOrigin,proxy:`${this.address.origin}${DEV_QUEUE_PROXY_PREFIX}/${this.resourceProxyToken}`},runtimeCache:{direct:`${this.runtimeCacheOrigin}${DEV_RUNTIME_CACHE_API_PREFIX}`,proxy:`${this.address.origin}${DEV_RUNTIME_CACHE_PREFIX}${this.resourceProxyToken}${DEV_RUNTIME_CACHE_API_PREFIX}`},...this.schedulesOrigin?{schedules:{direct:this.schedulesOrigin,proxy:`${this.address.origin}${DEV_SCHEDULES_PROXY_PREFIX}/${this.resourceProxyToken}`}}:{}}}getDevResourceMeta(){return{devResourceEndpoints:this.resourceEndpoints}}handleResourceServerRequest(req,res,origin,handler){if(!origin||!this.isAuthorizedResourceRequest(req,DEV_RESOURCE_TOKEN)){res.writeHead(401,{"WWW-Authenticate":"Bearer"}),res.end("Unauthorized");return}if(!isValidDevResourceHost(origin,req.headers.host)){res.writeHead(403),res.end("Forbidden");return}let pathname=new URL2(req.url||"/","http://127.0.0.1").pathname;handler(req,res,pathname).catch(err=>{output_manager_default.debug(`Local resource request failed for ${req.url||"/"}: ${(0,import_error_utils.errorToString)(err)}`),res.headersSent||res.writeHead(500),res.end("Internal Server Error")})}isAuthorizedResourceRequest(req,token){let authorization=req.headers.authorization;if(typeof authorization!="string")return!1;let encoder=new TextEncoder,actual=encoder.encode(authorization),expected=encoder.encode(`Bearer ${token}`);return actual.length===expected.length&&timingSafeEqual(actual,expected)}getBuilderDevEnv(match,env){let result={...env,...getDevSchedulesEnv(this.schedulesOrigin)};if(match.builderWithPkg.pkg.name!=="@vercel/container")return result;let endpoints=this.resourceEndpoints;return Object.assign(result,getDevSchedulesEnv(endpoints.schedules?.proxy,!0)),result.VERCEL_QUEUE_BASE_URL===endpoints.queues.direct&&Object.assign(result,getDevQueueEnv(endpoints.queues.proxy,result.VERCEL_HAS_WORKER_SERVICES!==void 0)),result.RUNTIME_CACHE_ENDPOINT===endpoints.runtimeCache.direct&&Object.assign(result,getDevRuntimeCacheEnv(endpoints.runtimeCache.proxy,"")),result}getSidecarDevMeta(match){let serviceCount=(this.sidecars??[]).filter(sidecar=>sidecar.builder.use!==match.use?!1:!sidecar.workspace||sidecar.workspace===".").length;return serviceCount>0?{serviceCount}:{}}async setupBuilderDevSidecars(){if(this.shouldUseServicesOrchestrator())return;let sidecars=this.sidecars??[];if(sidecars.length===0)return;Object.assign(this.envConfigs.runEnv,this.getDevQueueEnv());let services=sidecars.map(toOrchestratorService),orchestrator=new ServicesOrchestrator({services,cwd:this.cwd,repoRoot:this.repoRoot,env:this.envConfigs.allEnv,proxyOrigin:this.address.origin,resourceEndpoints:this.resourceEndpoints,useImplicitEnvInjection:!1,preferServiceBuilder:!0,onQueueSubscriptions:(serviceName,subscriptions)=>this.queueBroker?.updateServiceSubscriptions(serviceName,subscriptions)});this.sidecarOrchestrator=orchestrator,this.queueBroker?.registerServices(services);try{await orchestrator.startAll()}catch(err){throw await orchestrator.stopAll(),this.sidecarOrchestrator=void 0,this.sidecars=[],err}output_manager_default.log(`Started ${sidecars.length} development ${(0,import_pluralize2.default)("sidecar",sidecars.length)}`)}async exit(code=1){await this.stop(code),process.exit(code)}enqueueFsEvent(type,path6){this.bulkRedirectsResolvedPath&&(path6===this.bulkRedirectsResolvedPath||path6.startsWith(this.bulkRedirectsResolvedPath+sep2))&&(this.bulkRedirectsDirty=!0),this.watchAggregationEvents.push({type,path:path6}),this.watchAggregationId===null&&(this.watchAggregationId=setTimeout(()=>{let events=this.watchAggregationEvents.slice();this.watchAggregationEvents.length=0,this.watchAggregationId=null,this.handleFilesystemEvents(events).catch(err=>{output_manager_default.prettyError(err),(0,import_error_utils.isError)(err)&&typeof err.stack=="string"&&output_manager_default.debug(err.stack)})},this.watchAggregationTimeout))}async handleFilesystemEvents(events){if(this.stopping)return;output_manager_default.debug(`Filesystem watcher notified of ${events.length} events`);let filesChanged=new Set,filesRemoved=new Set,distPaths=[];for(let buildMatch of this.buildMatches.values())for(let buildResult of buildMatch.buildResults.values())buildResult.distPath&&distPaths.push(buildResult.distPath);if(events=events.filter(event=>distPaths.every(distPath=>!event.path.startsWith(distPath))),events.length!==0){this.functionReconciliations++;try{this.configGeneration++,this.functionDiscovery=void 0;for(let event of events)event.type==="add"?await this.handleFileCreated(event.path,filesChanged,filesRemoved):event.type==="unlink"?this.handleFileDeleted(event.path,filesChanged,filesRemoved):event.type==="change"&&await this.handleFileModified(event.path,filesChanged,filesRemoved);let vercelConfig=await this.getVercelConfig();if(this.stopping)return;await this.updateBuildMatches(vercelConfig);let filesChangedArray=[...filesChanged],filesRemovedArray=[...filesRemoved],needsRebuild=new Map;for(let match of this.buildMatches.values()){this.canonicalizeFunctionBuild(match);for(let[requestPath,result]of match.buildResults)if(!needsRebuild.has(result)&&Array.isArray(result.watch)){for(let pattern of result.watch)if(minimatches(filesChangedArray,pattern)||minimatches(filesRemovedArray,pattern)){needsRebuild.set(result,[requestPath,match]);break}}}if(needsRebuild.size>0){output_manager_default.debug(`Triggering ${needsRebuild.size} rebuilds`),filesChangedArray.length>0&&output_manager_default.debug(`Files changed: ${filesChangedArray.join(", ")}`),filesRemovedArray.length>0&&output_manager_default.debug(`Files removed: ${filesRemovedArray.join(", ")}`);for(let[result,[requestPath,match]]of needsRebuild)requestPath===null||await shouldServe(match,this.files,requestPath,this,vercelConfig)?this.triggerBuild(match,requestPath,null,vercelConfig,result,filesChangedArray,filesRemovedArray).catch(err=>{output_manager_default.warn(`An error occurred while rebuilding \`${match.src}\`:`),console.error(err.stack)}):output_manager_default.debug(`Not rebuilding because \`shouldServe()\` returned \`false\` for "${match.use}" request path "${requestPath}"`)}}finally{this.functionReconciliations--}}}async handleFileCreated(fsPath,changed,removed){let name=relative2(this.cwd,fsPath);try{await this.getVercelConfig(),this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath});let extensionless=this.getExtensionlessFile(name);extensionless&&(this.files[extensionless]=await import_build_utils9.FileFsRef.fromFsPath({fsPath})),fileChanged(name,changed,removed),output_manager_default.debug(`File created: ${name}`)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File created, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}handleFileDeleted(fsPath,changed,removed){let name=relative2(this.cwd,fsPath);output_manager_default.debug(`File deleted: ${name}`),fileRemoved(name,this.files,changed,removed);let extensionless=this.getExtensionlessFile(name);extensionless&&(output_manager_default.debug(`File deleted: ${extensionless}`),fileRemoved(extensionless,this.files,changed,removed))}async handleFileModified(fsPath,changed,removed){let name=relative2(this.cwd,fsPath);try{this.files[name]=await import_build_utils9.FileFsRef.fromFsPath({fsPath}),fileChanged(name,changed,removed),output_manager_default.debug(`File modified: ${name}`)}catch(err){if((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT")output_manager_default.debug(`File modified, but has since been deleted: ${name}`),fileRemoved(name,this.files,changed,removed);else throw err}}async updateBuildMatches(vercelConfig,isInitial=!1){let fileList=this.resolveBuildFiles(this.files),matches=await getBuildMatches(vercelConfig,this.cwd,this,fileList),sources=matches.map(m=>m.src);isInitial&&fileList.length===0&&output_manager_default.warn("There are no files inside your deployment.");let ops=[];for(let src of this.buildMatches.keys())if(!sources.includes(src)){output_manager_default.debug(`Removing build match for "${src}"`);let match=this.buildMatches.get(src);match&&ops.push(shutdownBuilder(match)),this.buildMatches.delete(src)}await Promise.all(ops);let blockingBuilds=[];for(let match of matches){let currentMatch=this.buildMatches.get(match.src);if(!buildMatchEquals(currentMatch,match)&&(output_manager_default.debug(`Adding build match for "${match.src}" with "${match.use}"`),this.buildMatches.set(match.src,match),!isInitial&&needsBlockingBuild(match))){let buildPromise=executeBuild(vercelConfig,this,this.files,match,null,!1);blockingBuilds.push(buildPromise)}}blockingBuilds.length>0&&(output_manager_default.debug(`Waiting for ${blockingBuilds.length} "blocking builds"`),this.blockingBuildsPromise=Promise.all(blockingBuilds).then(()=>{output_manager_default.debug('Cleaning up "blockingBuildsPromise" after successful resolve'),this.blockingBuildsPromise=null}).catch(err=>{output_manager_default.debug(`Cleaning up "blockingBuildsPromise" after error: ${err}`),this.blockingBuildsPromise=null,err&&output_manager_default.prettyError(err)})),this.buildMatches=new Map([...this.buildMatches.entries()].sort((matchA,matchB)=>sortBuilders(matchA[1],matchB[1])))}async getLocalEnv(fileName,base){let filePath=join4(this.cwd,fileName),env={};try{let dotenv=await import_fs_extra.default.readFile(filePath,"utf8");output_manager_default.debug(`Using local env: ${filePath}`),env=(0,import_dotenv.parse)(dotenv),env=this.injectSystemValuesInDotenv(env)}catch(err){if(!(0,import_error_utils.isErrnoException)(err)||err.code!=="ENOENT")throw err}try{return{...this.validateEnvConfig(fileName,base||{},env)}}catch(err){if(err instanceof MissingDotenvVarsError)this.reportError(err),await this.exit();else throw err}return{}}getVercelConfig(){if(this.getVercelConfigPromise)return this.getVercelConfigPromise;this.getVercelConfigPromise=(async()=>{for(;;){let generation=this.configGeneration;try{let config=await this._getVercelConfig();if(this.stopping||generation===this.configGeneration)return config}catch(err){if(this.stopping||generation===this.configGeneration)throw err}this.functionDiscovery=void 0}})();let clear=this.clearVercelConfigPromise;return this.getVercelConfigPromise.then(clear,clear),this.getVercelConfigPromise}get devCommand(){return this.getDevCommand(this.projectSettings)}getDevCommand(projectSettings){if(projectSettings?.devCommand)return projectSettings.devCommand;if(projectSettings?.framework){let frameworkSlug=projectSettings.framework,framework=import_frameworks3.frameworkList.find(f=>f.slug===frameworkSlug);if(framework){let defaults=framework.settings.devCommand.value;if(defaults)return defaults}if((0,import_build_utils9.shouldUseExperimentalBackends)(frameworkSlug))return"npx @vercel/cervel dev"}}getFunctionDiscovery(options){let key=JSON.stringify(options);if(!this.functionDiscovery||this.functionDiscovery.key!==key){let promise=collectDevFunctions(options);this.functionDiscovery={key,promise},promise.catch(()=>{this.functionDiscovery?.promise===promise&&(this.functionDiscovery=void 0)})}return this.functionDiscovery.promise}getDevFunction(outputPath){return this.functionRegistry.functions.get(outputPath)}getDevSchedules(){return this.functionRegistry.schedules}async dispatchSchedule({delivery,signal}){if(signal.throwIfAborted(),this.stopping)throw new Error("Local Schedules is stopping");if(delivery.type==="queue"){if(!this.queueBroker)throw new Error("Local Queue broker is not ready");this.queueBroker.enqueue(delivery.topic,Buffer.from(JSON.stringify(delivery.message)),"application/json");return}if(delivery.type==="path"){if(!this.devProcessOrigin)throw new Error(`Schedule path "${delivery.path}" is not ready because the dev server is unavailable`);signal.throwIfAborted();let response=await directFetch(`${this.devProcessOrigin}${delivery.path}`,{method:delivery.requestMethod,signal});if(!response.ok)throw new Error(`Schedule path "${delivery.path}" returned HTTP ${response.status}`);return}let invoke=this.resolveDevFunction(delivery.function);if(!invoke)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);signal.throwIfAborted();let onAbort=()=>{},aborted=new Promise((_,reject)=>{onAbort=()=>reject(signal.reason),signal.addEventListener("abort",onAbort,{once:!0})});try{let result=await Promise.race([aborted,invoke({method:"POST",headers:delivery.headers,body:Buffer.alloc(0),signal})]);if(!result)throw new Error(`Schedule function "${delivery.function}" is missing or not ready`);if(!result.ok)throw new Error(`Schedule function "${delivery.function}" returned HTTP ${result.status}`)}finally{signal.removeEventListener("abort",onAbort)}}resolveDevFunction(outputPath){let fn2=this.getDevFunction(outputPath);if(!fn2||this.stopping)return null;if(fn2.invocation.type==="http"){if(!this.devProcessOrigin)return null}else if(!this.functionDispatchReady||this.functionReconciliations>0||!this.getDevFunctionMatch(fn2))return null;return request=>this.invokeDevFunction(outputPath,request)}getDevFunctionMatch(fn2){if(fn2.invocation.type!=="entrypoint"||fn2.scope.target!=="builder")return;let{entrypoint}=fn2.invocation;return[...this.buildMatches.values()].find(match=>match.entrypoint===entrypoint&&match.use===fn2.scope.build.use&&(0,import_fast_deep_equal.default)(match.config??{},fn2.scope.build.config??{}))}canonicalizeFunctionBuild(match){if(![...this.functionRegistry.functions.values()].some(fn2=>this.getDevFunctionMatch(fn2)===match))return!1;if(match.buildResults.size&&!(match.buildResults.size===1&&match.buildResults.has(null))){let results=[...match.buildResults.values()],result=results[results.length-1];result.watch=[...new Set(results.flatMap(result2=>result2.watch))],match.buildResults.clear(),match.buildResults.set(null,result)}return!0}async invokeDevFunction(outputPath,request){request.signal?.throwIfAborted();let fn2=this.getDevFunction(outputPath);if(!fn2||!this.resolveDevFunction(outputPath))return null;let generation=this.configGeneration,isCurrent=()=>!this.stopping&&generation===this.configGeneration&&this.getDevFunction(outputPath)===fn2;if(fn2.invocation.type==="http"){let response=await directFetch(`${this.devProcessOrigin}${fn2.invocation.pathname}`,{...request,redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}let match=this.getDevFunctionMatch(fn2),config=this.functionConfig,req=new http.IncomingMessage(new Socket);req.method=request.method,req.url=`/${outputPath}`,req.headers={host:this.address.host,...request.headers};let requestId=generateRequestId(this.podId,!0),currentMatch=()=>!request.signal?.aborted&&isCurrent()&&this.getDevFunctionMatch(fn2)===match,devServerResult=await this.startBuildMatchDevServer(match,outputPath);if(devServerResult){let{port,pid,shutdown,persistent}=devServerResult;this.shutdownCallbacks.set(pid,shutdown);try{if(!currentMatch())return null;let response=await directFetch(`http://127.0.0.1:${port}/${outputPath}`,{...request,headers:nodeHeadersToFetchHeaders({...req.headers,...this.getProxyHeaders(req,requestId,!0)}),redirect:"manual"});return await response.arrayBuffer(),{ok:response.ok,status:response.status}}finally{let current=this.getDevFunction(outputPath);(this.stopping||!persistent||!current||this.getDevFunctionMatch(current)!==match)&&this.shutdownCallbacks.has(pid)&&await this.killBuilderDevServer(pid)}}if(!currentMatch())return null;let{entrypoint}=fn2.invocation,getAsset=()=>match.buildOutput[(match.buildResultVersion??match.builderWithPkg.builder.version)===2?outputPath:entrypoint];this.canonicalizeFunctionBuild(match);let asset=getAsset();if((!asset||this.inProgressBuilds.get(match)?.size)&&(await this.triggerBuild(match,null,null,config),asset=getAsset()),!currentMatch())return null;if(!asset||asset.type!=="Lambda"||!asset.fn)return{ok:!1,status:404};let result=await this.invokeBuiltLambda(asset,req,requestId,request.body);return{ok:result.statusCode>=200&&result.statusCode<300,status:result.statusCode}}async startBuildMatchDevServer(match,requestPath){let{builder}=match.builderWithPkg;if(!builder.startDevServer)return null;let{envConfigs,files,devCacheDir,cwd:workPath}=this;return builder.startDevServer({files,entrypoint:match.entrypoint,workPath,config:match.config||{},repoRootPath:this.repoRoot,meta:{isDev:!0,...this.getDevResourceMeta(),requestPath,devCacheDir,...this.getSidecarDevMeta(match),env:this.getBuilderDevEnv(match,{...envConfigs.runEnv,VERCEL_DEBUG_PREFIX:output_manager_default.debugEnabled?"[builder]":void 0}),buildEnv:{...envConfigs.buildEnv}}})}invokeBuiltLambda(asset,req,requestId,body){let payload={method:req.method||"GET",host:req.headers.host,path:req.url||"/",headers:{...req.headers,...this.getProxyHeaders(req,requestId,!0)},encoding:"base64",body:body.toString("base64")};return asset.fn({Action:"Invoke",body:JSON.stringify(payload)})}async _getVercelConfig(){let generation=this.configGeneration,{compileVercelConfig}=await import("../../chunks/compile-vercel-config-2HBWORW5.js"),compiled=await compileVercelConfig(this.cwd),configPath=getLocalPathConfig(this.cwd,!!compiled.sourceFile),[pkg=null,vercelConfig={version:2,[import_client.fileNameSymbol]:"vercel.json"}]=await Promise.all([this.readJsonFile("package.json"),this.readJsonFile(configPath,!0)]);await this.validateVercelConfig(vercelConfig);let functionConfig=structuredClone(vercelConfig),sourceFiles;for(let[name,service]of Object.entries(this.queueBroker?vercelConfig.services??vercelConfig.experimentalServicesV2??{}:{}))if(Object.values(service.functions??{}).some(fn2=>fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta")))throw dev.DEV_QUEUE_FUNCTION_UNSUPPORTED({sourceFile:`services.${name}.functions`,reason:"service-hosted function queue triggers are not supported locally yet"});let nextProjectSettings={...this.originalProjectSettings,...pickOverrides(vercelConfig)},{error:routeError,routes:maybeRoutes}=(0,import_routing_utils3.getTransformedRoutes)(vercelConfig);routeError&&(this.reportError(routeError),await this.exit()),vercelConfig.routes=maybeRoutes||[];let hasServices=(this.services?.length??0)>0,hasResolvedServices=!!this.services&&this.services.length>0,{schedules}=functionConfig,scheduleEntrypointPlan;if(!hasResolvedServices&&schedules?.some(import_schedule_entrypoint.hasScheduleEntrypointTarget)&&(sourceFiles=(await staticFiles(this.cwd,{})).map(f=>relative2(this.cwd,f)),scheduleEntrypointPlan=(0,import_schedule_entrypoint.planScheduleEntrypoints)({schedules,files:sourceFiles,framework:nextProjectSettings.framework,functions:functionConfig.functions})),!vercelConfig.experimentalServices&&!hasResolvedServices&&(!vercelConfig.builds||vercelConfig.builds.length===0)){let{projectSettings,cleanUrls,trailingSlash}=vercelConfig,files=sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative2(this.cwd,f));sourceFiles=files;let detectionOptions={tag:"latest",reservedFunctionFiles:scheduleEntrypointPlan?.reservedFunctionFiles,bunVersion:vercelConfig.bunVersion,functions:vercelConfig.functions,projectSettings:projectSettings||nextProjectSettings,featHandleMiss:!0,cleanUrls,trailingSlash,proxy:vercelConfig.proxy,workPath:this.cwd},detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions);for(;detectedBuilders.errors?.length===1&&detectedBuilders.errors[0].code==="unused_function";){let error2=detectedBuilders.errors[0],unmatchedTrigger=Object.entries(detectionOptions.functions??{}).find(([pattern,fn2])=>error2.message.startsWith(`The pattern "${pattern}" defined in \`functions\` `)&&fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta"||trigger.type==="schedule/v1beta"));if(!unmatchedTrigger)break;detectionOptions.functions={...detectionOptions.functions},delete detectionOptions.functions[unmatchedTrigger[0]],detectedBuilders=await(0,import_detect_builders_with_services.detectBuildersWithServices)(files,pkg,detectionOptions)}let{builders,warnings,errors,defaultRoutes,redirectRoutes,rewriteRoutes,errorRoutes}=detectedBuilders,hostRewriteRoutes=detectedBuilders.hostRewriteRoutes;if(errors){if(this.functionConfig)throw errors[0];this.reportError(errors[0]),await this.exit()}if(warnings?.length>0&&warnings.forEach(warning=>output_manager_default.warn(warning.message,null,warning.link,warning.action)),builders){let buildpackRuntime=builders.map(getBuildpackRuntime).find(runtime=>runtime!==void 0);if(buildpackRuntime)throw buildpackDevUnsupportedError(buildpackRuntime);vercelConfig.builds=vercelConfig.builds||[],vercelConfig.builds.push(...builders),delete vercelConfig.functions}let serviceRewrites=detectedBuilders.serviceRewrites,serviceRewriteRoutes=serviceRewrites&&serviceRewrites.length>0?(0,import_routing_utils3.convertRewrites)(serviceRewrites):null,routes=[];routes.push(...redirectRoutes||[]),routes=(0,import_routing_utils3.appendRoutesToPhase)({routes,newRoutes:hostRewriteRoutes??null,phase:null}),routes.push(...(0,import_routing_utils3.appendRoutesToPhase)({routes:vercelConfig.routes,newRoutes:[...rewriteRoutes||[],...serviceRewriteRoutes||[]],phase:"filesystem"})),routes=(0,import_routing_utils3.appendRoutesToPhase)({routes,newRoutes:errorRoutes,phase:"error"}),routes.push(...defaultRoutes||[]),vercelConfig.routes=routes}else if(hasResolvedServices&&vercelConfig.proxy){let{entrypoint}=vercelConfig.proxy;await import_fs_extra.default.pathExists(join4(this.cwd,entrypoint))||(output_manager_default.error(`The proxy entrypoint \`${entrypoint}\` does not exist. Set \`proxy.entrypoint\` to an existing \`.js\` or \`.ts\` file.`),await this.exit()),vercelConfig.builds=vercelConfig.builds||[],vercelConfig.builds.push((0,import_fs_detectors2.getProxyBuilder)(vercelConfig.proxy,"latest",vercelConfig.functions))}if(this.sidecars===void 0){let services=(this.services??[]).filter(import_build_utils9.isExperimentalServiceV2);this.sidecars=await collectBuilderDevSidecars({builds:this.shouldUseServicesOrchestrator()?services.map(service=>service.builder):vercelConfig.builds??[],workPath:this.cwd,services})}scheduleEntrypointPlan&&(vercelConfig.builds??=[{src:"**",use:"@vercel/static"}],(0,import_schedule_entrypoint.assertNoScheduleEntrypointSourceConflict)(vercelConfig.builds,scheduleEntrypointPlan),vercelConfig.builds.push(...scheduleEntrypointPlan.builds));let functionBuilds=[...vercelConfig.builds??[]];Array.isArray(vercelConfig.builds)&&((this.getDevCommand(nextProjectSettings)||hasServices)&&(vercelConfig.builds=vercelConfig.builds.filter(this.shouldBuildInDev)),vercelConfig.builds.sort(sortBuilders)),vercelConfig.routes=(vercelConfig.routes||[]).filter(route=>"has"in route?(this.vercelConfigWarning||(this.vercelConfigWarning=!0,output_manager_default.warn(`The "has" property in ${vercelConfig[import_client.fileNameSymbol]} will be ignored during development. Deployments will work as expected.`)),!1):!0);let[runEnv,buildEnv]=await Promise.all([this.getLocalEnv(".env",vercelConfig.env),this.getLocalEnv(".env.build",vercelConfig.build?.env)]),allEnv={...buildEnv,...runEnv};if(Object.keys(allEnv).length===0){let envValues={...this.envValues};this.address.host&&(envValues.VERCEL_URL=this.address.host),allEnv={...envValues},runEnv={...envValues},buildEnv={...envValues}}runEnv.NODE_ENV??=process.env.NODE_ENV??"development",allEnv.NODE_ENV??=runEnv.NODE_ENV,runEnv.NOW_REGION="dev1",buildEnv.NOW_REGION="dev1",allEnv.NOW_REGION="dev1",allEnv.VERCEL_ENV="development",allEnv.VERCEL="1",this.projectId&&!process.env.VERCEL_PROJECT_ID&&("VERCEL_PROJECT_ID"in allEnv||(allEnv.VERCEL_PROJECT_ID=this.projectId),"VERCEL_PROJECT_ID"in runEnv||(runEnv.VERCEL_PROJECT_ID=this.projectId)),this.orgId&&!process.env.VERCEL_ORG_ID&&("VERCEL_ORG_ID"in allEnv||(allEnv.VERCEL_ORG_ID=this.orgId),"VERCEL_ORG_ID"in runEnv||(runEnv.VERCEL_ORG_ID=this.orgId)),nextProjectSettings?.autoExposeSystemEnvs&&(runEnv.VERCEL_REGION="dev1"),runEnv.VERCEL_CLI_VERSION=pkg_default.version,Object.assign(runEnv,this.getDevQueueEnv()),Object.assign(runEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(allEnv,getDevSchedulesEnv(this.schedulesOrigin)),Object.assign(runEnv,this.getDevRuntimeCacheEnv(runEnv));let hasQueueFunctions=Object.values(functionConfig.functions??{}).some(fn2=>fn2.experimentalTriggers?.some(trigger=>trigger.type==="queue/v2beta"));if(this.queueBroker&&hasQueueFunctions&&hasResolvedServices)throw dev.DEV_QUEUE_FUNCTION_UNSUPPORTED({sourceFile:"functions",reason:"service-hosted function queue triggers are not supported locally yet"});let registry=await this.getFunctionDiscovery({scopes:(hasResolvedServices?[]:functionBuilds).map(build=>({build,target:vercelConfig.builds?.includes(build)?"builder":"framework"})),workPath:this.cwd,files:(sourceFiles??(await staticFiles(this.cwd,{})).map(f=>relative2(this.cwd,f))).sort(),config:functionConfig,env:{...process.env,...allEnv,...this.getDevQueueEnv(),...getDevSchedulesEnv(this.schedulesOrigin),...this.getDevRuntimeCacheEnv(allEnv)}}),subscriptions,staticSchedules,sourceChanged;try{subscriptions=deriveQueueSubscriptions(registry),this.queueBroker?.validateFunctionSubscriptions(subscriptions),staticSchedules=collectStaticSchedules(scheduleEntrypointPlan&&schedules?(0,import_schedule_entrypoint.resolveScheduleEntrypointTargets)(schedules,scheduleEntrypointPlan):functionConfig.schedules,registry),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&this.scheduleBroker.validateStatic(staticSchedules)}catch(err){throw this.functionDiscovery=void 0,err}let{unmatchedPatterns}=registry;if(await this.refreshBulkRedirects(vercelConfig.bulkRedirectsPath),this.devCommandStarts.size&&await Promise.all(this.devCommandStarts),this.stopping||generation!==this.configGeneration)return vercelConfig;let restartForFunctionEnv=!!(this.devCommandEnv&&[...registry.functions.values()].some(fn2=>fn2.invocation.type==="http")&&!(0,import_fast_deep_equal.default)(this.devCommandEnv,allEnv)),previousProcess=this.devProcess,previousOrigin=this.devProcessOrigin,previousCommand=this.currentDevCommand,previousEnv=this.devCommandEnv,previousRuntime={projectSettings:this.projectSettings,allEnv:previousEnv??this.envConfigs.allEnv},restarted,validated=!1;try{if(this.initialDevCommandStarted&&await this.runDevCommand(restartForFunctionEnv,{projectSettings:nextProjectSettings,allEnv},origin=>{restarted={origin}}),this.stopping||generation!==this.configGeneration)return vercelConfig;this.queueBroker?.validateFunctionSubscriptions(subscriptions),sourceChanged=!(0,import_fast_deep_equal.default)(this.staticSchedulesSnapshot,staticSchedules),sourceChanged&&(this.scheduleBroker.validateStatic(staticSchedules),this.scheduleBroker.reconcileStatic(staticSchedules),this.staticSchedulesSnapshot=structuredClone(staticSchedules)),validated=!0}finally{!this.stopping&&!validated&&(this.devProcess!==previousProcess||this.devProcessOrigin!==previousOrigin||this.currentDevCommand!==previousCommand||this.devCommandEnv!==previousEnv)&&await this.runDevCommand(!0,previousRuntime)}this.projectSettings=nextProjectSettings,this.caseSensitive=hasNewRoutingProperties(vercelConfig),this.apiDir=(0,import_fs_detectors2.detectApiDirectory)(vercelConfig.builds||[]),this.apiExtensions=(0,import_fs_detectors2.detectApiExtensions)(vercelConfig.builds||[]),this.envConfigs={buildEnv,runEnv,allEnv},this.functionRegistry=registry,this.functionConfig=vercelConfig,restarted&&(this.devProcessOrigin=restarted.origin),this.queueBroker?.setFunctionSubscriptions(subscriptions,outputPath=>this.resolveDevFunction(outputPath));for(let pattern of unmatchedPatterns)if(!this.unmatchedQueuePatterns.has(pattern)){let warning=dev.DEV_QUEUE_FUNCTION_UNMATCHED({pattern});output_manager_default.warn(`[${warning.name}] ${warning.message} ${warning.fix}`)}return this.unmatchedQueuePatterns=new Set(unmatchedPatterns),vercelConfig}async refreshBulkRedirects(bulkRedirectsPath){let configPath=bulkRedirectsPath??null;if(configPath===this.bulkRedirectsLastPath&&!this.bulkRedirectsDirty)return;if(this.bulkRedirectsLastPath=configPath,this.bulkRedirectsDirty=!1,this.bulkRedirectsResolvedPath=configPath?resolveBulkRedirectsPath(this.cwd,configPath):null,!configPath){this.bulkRedirects=null,this.bulkRedirectsSignature=null;return}let signature=await getBulkRedirectsSignature(this.cwd,configPath);if(signature!==this.bulkRedirectsSignature){this.bulkRedirectsSignature=signature;try{let result=await loadBulkRedirects(this.cwd,configPath);this.bulkRedirects=result.table;for(let warning of result.warnings)output_manager_default.warn(warning);let count=result.table.size;count>0&&output_manager_default.log(`Loaded ${count} bulk ${(0,import_pluralize2.default)("redirect",count)} from ${configPath}`)}catch(err){this.bulkRedirects=null,output_manager_default.warn(`Failed to load bulk redirects from "${configPath}": ${(0,import_error_utils.errorToString)(err)}`)}}}async readJsonFile(filePath,strict=!1){let rel,abs;isAbsolute3(filePath)?(rel=path4.relative(this.cwd,filePath),abs=filePath):(rel=filePath,abs=join4(this.cwd,filePath)),output_manager_default.debug(`Reading \`${rel}\` file`);try{let raw=await import_fs_extra.default.readFile(abs,"utf8"),parsed=(0,import_json_parse_better_errors.default)(raw);return parsed[import_client.fileNameSymbol]=rel,parsed}catch(err){if(strict&&!((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT"))throw err;if((0,import_error_utils.isError)(err))(0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT"?output_manager_default.debug(`No \`${rel}\` file present`):err.name==="SyntaxError"&&output_manager_default.warn(`There is a syntax error in the \`${rel}\` file: ${err.message}`);else throw err}}async tryValidateOrExit(config,validate){let message2=validate(config);message2&&(output_manager_default.error(message2),await this.exit(1))}async validateVercelConfig(config){if(config.version===1){if(this.functionConfig)throw dev.DEV_UNSUPPORTED_CONFIG_VERSION();this.reportError(dev.DEV_UNSUPPORTED_CONFIG_VERSION()),await this.exit(1);return}let error2=validateConfig(config);if(error2){if(this.functionConfig)throw error2;this.reportError(error2),await this.exit(1)}}validateEnvConfig(type,env={},localEnv={}){let missing=Object.entries(env).filter(([name,value])=>typeof value=="string"&&value.startsWith("@")&&!hasProp(localEnv,name)).map(([name])=>name);if(missing.length>0)throw new MissingDotenvVarsError(type,missing);let merged={...env,...localEnv},hasInvalidName=!1;for(let key of Object.keys(merged))/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)||(output_manager_default.warn(`Ignoring ${type.split(".").slice(1).reverse().join(" ")} var ${JSON.stringify(key)} because name is invalid`),hasInvalidName=!0,delete merged[key]);return hasInvalidName&&output_manager_default.log("The name contains invalid characters. Only letters, digits, and underscores are allowed. Furthermore, the name should not start with a digit"),merged}injectSystemValuesInDotenv(env){for(let name of Object.keys(env))name==="VERCEL_URL"?env.VERCEL_URL=this.address.host:name==="VERCEL_REGION"&&(env.VERCEL_REGION="dev1");return env}resolveBuildFiles(files){return Object.keys(files).filter(this.filter)}isWatcherIgnored(fsPath){let relativePath=relative2(this.cwd,fsPath);return relativePath===""?!1:!this.filter(relativePath)}start(...listenSpec){return this.startPromise||(this.startPromise=this._start(...listenSpec).catch(async err=>{throw await this.stop(),err})),this.startPromise}async _start(...listenSpec){if(this.stopping)return;if(!import_fs_extra.default.existsSync(this.cwd))throw dev.DEV_CWD_NOT_FOUND({cwd:this.cwd});if(!import_fs_extra.default.lstatSync(this.cwd).isDirectory())throw dev.DEV_CWD_NOT_DIRECTORY({cwd:this.cwd});let{ig}=await(0,import_client.getVercelIgnore)(this.cwd);this.filter=ig.createFilter();let address=null;for(;typeof address!="string";){if(this.stopping)return;try{address=(await(this.listenerStartup=(0,import_async_listen.listen)(this.server,...listenSpec))).toString()}catch(err){if((0,import_error_utils.isErrnoException)(err))if(output_manager_default.debug(`Got listen error: ${err.code}`),err.code==="EADDRINUSE")typeof listenSpec[0]=="number"?(output_manager_default.note(`Requested port ${import_chalk2.default.yellow(String(listenSpec[0]))} is already in use`),listenSpec[0]++):(this.reportError(dev.DEV_LISTEN_ADDRESS_IN_USE({address:String(listenSpec[0])})),process.exit(1));else throw err;else throw err}}if(this.stopping)return;this._address=new URL2(replaceLocalhost(address)),this.runtimeCache=new RuntimeCacheStore;let runtimeCacheListener=await(this.listenerStartup=listenOnDevResourcePort(this.runtimeCacheServer,{name:"Runtime Cache",flag:"--runtime-cache-port",defaultPort:DEV_RUNTIME_CACHE_DEFAULT_PORT,port:this.runtimeCachePort,reservedPorts:[this.queuePort,this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT].filter(port=>port!==void 0&&port!==0)}));if(this.stopping)return;this.runtimeCacheOrigin=runtimeCacheListener.origin,runtimeCacheListener.defaultPort!==void 0&&output_manager_default.warn(`Runtime Cache default port ${runtimeCacheListener.defaultPort} is unavailable; listening on ${runtimeCacheListener.port} instead.
|
|
56
56
|
External clients configured for ${runtimeCacheListener.defaultPort} will not reach this dev server. Pin a port with --runtime-cache-port.`);let queueListener=await(this.listenerStartup=listenOnDevResourcePort(this.queueServer,{name:"Vercel Queues",flag:"--queue-port",defaultPort:DEV_QUEUE_DEFAULT_PORT,port:this.queuePort,reservedPorts:[this.schedulesPort??DEV_SCHEDULES_DEFAULT_PORT]}));if(this.stopping)return;this.queueOrigin=queueListener.origin,queueListener.defaultPort!==void 0&&output_manager_default.warn(`Vercel Queues default port ${queueListener.defaultPort} is unavailable; listening on ${queueListener.port} instead.
|
|
57
57
|
External clients configured for ${queueListener.defaultPort} will not reach this dev server. Pin a port with --queue-port.`),this.queueBroker=new QueueBroker([],name=>this.orchestrator?.getServiceOrigin(name)??this.sidecarOrchestrator?.getServiceOrigin(name)??null);let schedulesListener=await(this.listenerStartup=listenOnDevResourcePort(this.schedulesServer,{name:"Vercel Schedules",flag:"--schedules-port",defaultPort:DEV_SCHEDULES_DEFAULT_PORT,port:this.schedulesPort}));if(this.stopping||(this.schedulesOrigin=schedulesListener.origin,this.schedulesSessionPublication=createLocalSchedulesSession(this.cwd,`http://127.0.0.1:${schedulesListener.port}`,this.projectId??"prj_local").then(async published=>{this.stopping?await published.dispose():this.schedulesSession=published}),await this.schedulesSessionPublication,this.stopping))return;schedulesListener.defaultPort!==void 0&&output_manager_default.print(import_chalk2.default.yellow(`! Vercel Schedules default port ${schedulesListener.defaultPort} is unavailable; listening on ${schedulesListener.port} instead.
|
|
58
58
|
Pin a port with --schedules-port for clients outside the dev server.
|