@vercel/cli-support 0.0.0 → 65.3.1
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/LICENSE +202 -0
- package/README.md +100 -3
- package/dist/chunks/add-5YZQTIQM.js +8 -0
- package/dist/chunks/add-A524QQ2H.js +8 -0
- package/dist/chunks/add-V4JMUHKO.js +8 -0
- package/dist/chunks/build-K2PVDJZ4.js +7 -0
- package/dist/chunks/chunk-22FDWPWY.js +7 -0
- package/dist/chunks/chunk-25565AGS.js +7 -0
- package/dist/chunks/chunk-2ACMWVTB.js +12 -0
- package/dist/chunks/chunk-2EYYB6YN.js +7 -0
- package/dist/chunks/chunk-2GHZGOWT.js +7 -0
- package/dist/chunks/chunk-2H3SB5RP.js +9 -0
- package/dist/chunks/chunk-2NABMKFV.js +29 -0
- package/dist/chunks/chunk-2PKEEQ5W.js +25 -0
- package/dist/chunks/chunk-2S6PE6GB.js +7 -0
- package/dist/chunks/chunk-2U7DJZSQ.js +21 -0
- package/dist/chunks/chunk-2WYYGGEO.js +7 -0
- package/dist/chunks/chunk-3ADDGPEN.js +7 -0
- package/dist/chunks/chunk-3AYYFYZG.js +7 -0
- package/dist/chunks/chunk-3G3FQYMW.js +7 -0
- package/dist/chunks/chunk-3JGBBS6V.js +7 -0
- package/dist/chunks/chunk-3KKFLKQG.js +7 -0
- package/dist/chunks/chunk-3LIKVGFT.js +8 -0
- package/dist/chunks/chunk-3XW7N4W3.js +9 -0
- package/dist/chunks/chunk-43GBAKL2.js +86 -0
- package/dist/chunks/chunk-4CACOKMS.js +7 -0
- package/dist/chunks/chunk-4NTBYNFR.js +17 -0
- package/dist/chunks/chunk-4SAVH3H7.js +7 -0
- package/dist/chunks/chunk-4UGHFESV.js +8 -0
- package/dist/chunks/chunk-4VFYJU37.js +7 -0
- package/dist/chunks/chunk-5IASAERQ.js +7 -0
- package/dist/chunks/chunk-5RMIM4S2.js +7 -0
- package/dist/chunks/chunk-67GZ5REA.js +7 -0
- package/dist/chunks/chunk-6IDNVZZR.js +7 -0
- package/dist/chunks/chunk-6ISAISGD.js +16 -0
- package/dist/chunks/chunk-6KVHNQW4.js +17 -0
- package/dist/chunks/chunk-6OVX3PWM.js +7 -0
- package/dist/chunks/chunk-6QKS6QK7.js +7 -0
- package/dist/chunks/chunk-6VH56CX2.js +19 -0
- package/dist/chunks/chunk-6Y2ZL5XJ.js +98 -0
- package/dist/chunks/chunk-76KGQU2G.js +7 -0
- package/dist/chunks/chunk-76SVVWPH.js +7 -0
- package/dist/chunks/chunk-773GOZIR.js +13 -0
- package/dist/chunks/chunk-7BGKE3JW.js +10 -0
- package/dist/chunks/chunk-7EJQLVWX.js +7 -0
- package/dist/chunks/chunk-7HV7O6DM.js +7 -0
- package/dist/chunks/chunk-7L2K4OKM.js +63 -0
- package/dist/chunks/chunk-7Y46LB43.js +14 -0
- package/dist/chunks/chunk-7YKFF6CE.js +7 -0
- package/dist/chunks/chunk-7Z3WUAO5.js +10 -0
- package/dist/chunks/chunk-A2RZZQEP.js +7 -0
- package/dist/chunks/chunk-ABZEMNDR.js +7 -0
- package/dist/chunks/chunk-ADLBLGT3.js +8 -0
- package/dist/chunks/chunk-AM46JVVN.js +7 -0
- package/dist/chunks/chunk-ANMDN3EG.js +9 -0
- package/dist/chunks/chunk-APZULWJC.js +8 -0
- package/dist/chunks/chunk-AWMQGOS2.js +7 -0
- package/dist/chunks/chunk-B4UE4LVE.js +7 -0
- package/dist/chunks/chunk-B4YYOSPY.js +7 -0
- package/dist/chunks/chunk-BBKEP7RO.js +7 -0
- package/dist/chunks/chunk-BL3HBRF6.js +12 -0
- package/dist/chunks/chunk-BLUPZPAS.js +7 -0
- package/dist/chunks/chunk-BPUANOGW.js +7 -0
- package/dist/chunks/chunk-BRQUZ5NC.js +7 -0
- package/dist/chunks/chunk-BS32OUOC.js +7 -0
- package/dist/chunks/chunk-BTI5TG6Q.js +7 -0
- package/dist/chunks/chunk-BUJITHGZ.js +8 -0
- package/dist/chunks/chunk-BVH2AEFE.js +7 -0
- package/dist/chunks/chunk-BZENIQ7N.js +7 -0
- package/dist/chunks/chunk-C6GY2G73.js +7 -0
- package/dist/chunks/chunk-CEMPU323.js +7 -0
- package/dist/chunks/chunk-COD3WAUI.js +7 -0
- package/dist/chunks/chunk-COM5YCHF.js +9 -0
- package/dist/chunks/chunk-CZSOZKHX.js +7 -0
- package/dist/chunks/chunk-D2BZMGHP.js +7 -0
- package/dist/chunks/chunk-D3AHZ5LI.js +7 -0
- package/dist/chunks/chunk-D6REP5QQ.js +15 -0
- package/dist/chunks/chunk-DFVNL5ML.js +7 -0
- package/dist/chunks/chunk-DGYHWXD2.js +10 -0
- package/dist/chunks/chunk-DUT4U5YY.js +7 -0
- package/dist/chunks/chunk-DWZBL4NK.js +7 -0
- package/dist/chunks/chunk-E2SADN6I.js +7 -0
- package/dist/chunks/chunk-E6CO6TUM.js +7 -0
- package/dist/chunks/chunk-EAUDC24V.js +9 -0
- package/dist/chunks/chunk-ECQIO5K3.js +7 -0
- package/dist/chunks/chunk-ETV3C2CV.js +7 -0
- package/dist/chunks/chunk-F2SWJEYV.js +8 -0
- package/dist/chunks/chunk-F4KY2TOK.js +7 -0
- package/dist/chunks/chunk-F53OKXYI.js +7 -0
- package/dist/chunks/chunk-F7AVGV4Y.js +7 -0
- package/dist/chunks/chunk-FBYA6LLM.js +7 -0
- package/dist/chunks/chunk-FDNYYENK.js +11 -0
- package/dist/chunks/chunk-FGFLTLEA.js +7 -0
- package/dist/chunks/chunk-FUX6LKNP.js +7 -0
- package/dist/chunks/chunk-G4T7VBGN.js +9 -0
- package/dist/chunks/chunk-GA277JFB.js +20 -0
- package/dist/chunks/chunk-GD7AV7BO.js +9 -0
- package/dist/chunks/chunk-GG5RME4X.js +7 -0
- package/dist/chunks/chunk-GHAY4PSD.js +7 -0
- package/dist/chunks/chunk-GVTXA6HG.js +7 -0
- package/dist/chunks/chunk-GYVJIIYL.js +7 -0
- package/dist/chunks/chunk-GZNDA6SV.js +8 -0
- package/dist/chunks/chunk-HCRD3JFL.js +7 -0
- package/dist/chunks/chunk-HEGJZJO7.js +7 -0
- package/dist/chunks/chunk-HRR57QNP.js +7 -0
- package/dist/chunks/chunk-IA3MXJRC.js +8 -0
- package/dist/chunks/chunk-ID663OJ7.js +7 -0
- package/dist/chunks/chunk-IEPW2YRH.js +7 -0
- package/dist/chunks/chunk-IGDG5CWT.js +7 -0
- package/dist/chunks/chunk-IKQTP764.js +7 -0
- package/dist/chunks/chunk-IQ7FPAI4.js +7 -0
- package/dist/chunks/chunk-IQKGQ2Y2.js +15 -0
- package/dist/chunks/chunk-ISWW3DKF.js +7 -0
- package/dist/chunks/chunk-IUXSJWL3.js +7 -0
- package/dist/chunks/chunk-IVSC7ZFJ.js +7 -0
- package/dist/chunks/chunk-IVSSTHB6.js +7 -0
- package/dist/chunks/chunk-J24BABG4.js +21 -0
- package/dist/chunks/chunk-JALVF3C2.js +7 -0
- package/dist/chunks/chunk-JELLVPCM.js +8 -0
- package/dist/chunks/chunk-JESNVRVR.js +7 -0
- package/dist/chunks/chunk-JLEJB6KM.js +7 -0
- package/dist/chunks/chunk-KH6565YH.js +8 -0
- package/dist/chunks/chunk-KNLGWGUE.js +57 -0
- package/dist/chunks/chunk-KRPY5FHJ.js +7 -0
- package/dist/chunks/chunk-KW6GSQXV.js +7 -0
- package/dist/chunks/chunk-L4NSF346.js +22 -0
- package/dist/chunks/chunk-LCHECISY.js +7 -0
- package/dist/chunks/chunk-LJBUJ23M.js +7 -0
- package/dist/chunks/chunk-LKLH6DZP.js +9 -0
- package/dist/chunks/chunk-LRYGNQ6C.js +8 -0
- package/dist/chunks/chunk-LSF7FY6X.js +7 -0
- package/dist/chunks/chunk-LSQREJXO.js +11 -0
- package/dist/chunks/chunk-LT3UK4K6.js +10 -0
- package/dist/chunks/chunk-LUBUI5GF.js +7 -0
- package/dist/chunks/chunk-MCRKBVZA.js +7 -0
- package/dist/chunks/chunk-MVGTMPMI.js +23 -0
- package/dist/chunks/chunk-MXTC4ZAQ.js +7 -0
- package/dist/chunks/chunk-NB2WLB3J.js +12 -0
- package/dist/chunks/chunk-NEFDNROD.js +7 -0
- package/dist/chunks/chunk-NQWGRKF4.js +7 -0
- package/dist/chunks/chunk-NTZ5WWYV.js +7 -0
- package/dist/chunks/chunk-NWGBDBZI.js +7 -0
- package/dist/chunks/chunk-NZ2TFADV.js +7 -0
- package/dist/chunks/chunk-OAM5NJCU.js +9 -0
- package/dist/chunks/chunk-OCQPXOTX.js +11 -0
- package/dist/chunks/chunk-OCR5CRTH.js +10 -0
- package/dist/chunks/chunk-OFDTADPQ.js +7 -0
- package/dist/chunks/chunk-OGPENBY2.js +7 -0
- package/dist/chunks/chunk-OKEBIUKZ.js +7 -0
- package/dist/chunks/chunk-OMCGXRSA.js +21 -0
- package/dist/chunks/chunk-OO572JUC.js +7 -0
- package/dist/chunks/chunk-OPORM35X.js +7 -0
- package/dist/chunks/chunk-OQCMRU3J.js +10 -0
- package/dist/chunks/chunk-OQPXJCMK.js +32 -0
- package/dist/chunks/chunk-OWOWPOIE.js +23 -0
- package/dist/chunks/chunk-PADL3C6Z.js +7 -0
- package/dist/chunks/chunk-PFD7LETF.js +7 -0
- package/dist/chunks/chunk-PFNYWWLI.js +7 -0
- package/dist/chunks/chunk-PFPJLIFF.js +33 -0
- package/dist/chunks/chunk-PSOVLGHP.js +7 -0
- package/dist/chunks/chunk-PUKYAALC.js +7 -0
- package/dist/chunks/chunk-PVASGBEF.js +7 -0
- package/dist/chunks/chunk-Q5ODLDCU.js +7 -0
- package/dist/chunks/chunk-Q7D7RGXM.js +7 -0
- package/dist/chunks/chunk-QB7F3UAP.js +7 -0
- package/dist/chunks/chunk-QHJLRTVY.js +7 -0
- package/dist/chunks/chunk-QMCHGGDX.js +10 -0
- package/dist/chunks/chunk-QZX7VG2V.js +9 -0
- package/dist/chunks/chunk-R6BEOVTU.js +7 -0
- package/dist/chunks/chunk-RLKS5G6C.js +12 -0
- package/dist/chunks/chunk-RM3ZDRYE.js +7 -0
- package/dist/chunks/chunk-RRDNKB2X.js +7 -0
- package/dist/chunks/chunk-RRREFECI.js +7 -0
- package/dist/chunks/chunk-RUXO73ON.js +7 -0
- package/dist/chunks/chunk-RW3X523R.js +8 -0
- package/dist/chunks/chunk-S3L2OHPO.js +7 -0
- package/dist/chunks/chunk-S4SJ7GIZ.js +7 -0
- package/dist/chunks/chunk-S5IWVPYT.js +32 -0
- package/dist/chunks/chunk-SACGQMVQ.js +13 -0
- package/dist/chunks/chunk-SCV7XEEO.js +7 -0
- package/dist/chunks/chunk-SF4E3AQ3.js +7 -0
- package/dist/chunks/chunk-SKYDLHEZ.js +7 -0
- package/dist/chunks/chunk-SLI2O5X7.js +63 -0
- package/dist/chunks/chunk-SXOSF4O6.js +39 -0
- package/dist/chunks/chunk-TAAWMNNL.js +7 -0
- package/dist/chunks/chunk-TG2RCYTH.js +7 -0
- package/dist/chunks/chunk-TKBORMUF.js +7 -0
- package/dist/chunks/chunk-TO5PJDEN.js +7 -0
- package/dist/chunks/chunk-TPNOSQZ3.js +15 -0
- package/dist/chunks/chunk-TZFDVQ72.js +27 -0
- package/dist/chunks/chunk-U4Z2MMOF.js +301 -0
- package/dist/chunks/chunk-U56NHYAH.js +7 -0
- package/dist/chunks/chunk-UJSW56GS.js +9 -0
- package/dist/chunks/chunk-UKQMYTWW.js +9 -0
- package/dist/chunks/chunk-ULHNMQ7C.js +7 -0
- package/dist/chunks/chunk-UNEGQPD3.js +7 -0
- package/dist/chunks/chunk-URPEIX6M.js +7 -0
- package/dist/chunks/chunk-UVHKXCR5.js +11 -0
- package/dist/chunks/chunk-V6Y6UK6B.js +43 -0
- package/dist/chunks/chunk-V7BEC3E4.js +10 -0
- package/dist/chunks/chunk-VMMMBWD3.js +7 -0
- package/dist/chunks/chunk-VOCZ34ON.js +7 -0
- package/dist/chunks/chunk-VQSLPYAF.js +7 -0
- package/dist/chunks/chunk-VT6RIZJH.js +7 -0
- package/dist/chunks/chunk-WBF36MYT.js +16 -0
- package/dist/chunks/chunk-WCWP4GBR.js +7 -0
- package/dist/chunks/chunk-WGXKX24Q.js +7 -0
- package/dist/chunks/chunk-X4762EE4.js +7 -0
- package/dist/chunks/chunk-XB4SKARZ.js +29 -0
- package/dist/chunks/chunk-XGTKHQTT.js +7 -0
- package/dist/chunks/chunk-XOETL6DB.js +96 -0
- package/dist/chunks/chunk-XP3FT56R.js +27 -0
- package/dist/chunks/chunk-XR6QY7RR.js +7 -0
- package/dist/chunks/chunk-XXXRTHTP.js +8 -0
- package/dist/chunks/chunk-XZV4BFM5.js +7 -0
- package/dist/chunks/chunk-Y6AGOERS.js +8 -0
- package/dist/chunks/chunk-YHPPP3SF.js +7 -0
- package/dist/chunks/chunk-YHQ7PPXP.js +7 -0
- package/dist/chunks/chunk-YK7XLFU2.js +24 -0
- package/dist/chunks/chunk-YN3C5BL5.js +7 -0
- package/dist/chunks/chunk-ZF27J6FQ.js +7 -0
- package/dist/chunks/chunk-ZFRNVIHI.js +7 -0
- package/dist/chunks/chunk-ZH6KHD55.js +20 -0
- package/dist/chunks/cjs-2SMN43VH.js +54 -0
- package/dist/chunks/clear-ZS4KQ7OT.js +8 -0
- package/dist/chunks/compile-vercel-config-3IYM2CHC.js +7 -0
- package/dist/chunks/config-N2SBVW4T.js +8 -0
- package/dist/chunks/config-ZFIC7N4D.js +7 -0
- package/dist/chunks/config-validator.mjs +1 -0
- package/dist/chunks/connect-git-provider-FS5Q2HO4.js +7 -0
- package/dist/chunks/constants-ICJL2EO5.js +7 -0
- package/dist/chunks/create-project-IKCB6MB2.js +7 -0
- package/dist/chunks/delete-2ZE2NVHI.js +10 -0
- package/dist/chunks/delete-AL57HZDQ.js +9 -0
- package/dist/chunks/detect-projects-OD4JEAW2.js +7 -0
- package/dist/chunks/detect-services-MOXTX5XG.js +7 -0
- package/dist/chunks/disable-MKI3BKNH.js +7 -0
- package/dist/chunks/discard-SI4H7ST3.js +14 -0
- package/dist/chunks/dist-33WTJLVQ.js +7 -0
- package/dist/chunks/dist-RXYNZPEA.js +7 -0
- package/dist/chunks/edit-DNWH6SPE.js +8 -0
- package/dist/chunks/edit-WYNWDFUJ.js +9 -0
- package/dist/chunks/enable-J6MMYPYF.js +7 -0
- package/dist/chunks/esm-33752ISR.js +7 -0
- package/dist/chunks/esm-4JKEE7PC.js +7 -0
- package/dist/chunks/esm-BYG5BWYH.js +9 -0
- package/dist/chunks/esm-DFFBNKNU.js +20 -0
- package/dist/chunks/esm-IF453UWS.js +7 -0
- package/dist/chunks/esm-LABWDJ72.js +7 -0
- package/dist/chunks/esm-TG37FXTU.js +9 -0
- package/dist/chunks/exec-OZSY46V6.js +16372 -0
- package/dist/chunks/export-MHSH7QCX.js +19 -0
- package/dist/chunks/fetch-proxy-45DGILKR.js +67 -0
- package/dist/chunks/future-FFOGTKMF.js +7 -0
- package/dist/chunks/generate-cert-for-deploy-YZKNGAEQ.js +7 -0
- package/dist/chunks/image-7METSS6F.js +7 -0
- package/dist/chunks/import-builders-GM2SERWV.js +7 -0
- package/dist/chunks/inspect-A7WJQQZO.js +15 -0
- package/dist/chunks/inspect-DI434TAM.js +19 -0
- package/dist/chunks/inspect-H2Q7XOWN.js +13 -0
- package/dist/chunks/inspect-H5JC2XKI.js +9 -0
- package/dist/chunks/inspect-IAWVHJXQ.js +20 -0
- package/dist/chunks/list-ELEUTZWJ.js +12 -0
- package/dist/chunks/list-INRPH25K.js +10 -0
- package/dist/chunks/list-WWU734RK.js +16 -0
- package/dist/chunks/login-R5NQRPQC.js +7 -0
- package/dist/chunks/login-ZF2TLCQB.js +9 -0
- package/dist/chunks/logs-UD7FEXZ7.js +7 -0
- package/dist/chunks/ls-5ZEAKKPQ.js +8 -0
- package/dist/chunks/ls-IXRLAJ4L.js +11 -0
- package/dist/chunks/ls-LIGIBVAT.js +12 -0
- package/dist/chunks/ls-MCQ2NS65.js +8 -0
- package/dist/chunks/ls-S5E2NQMI.js +12 -0
- package/dist/chunks/ls-V2ZSIVO3.js +12 -0
- package/dist/chunks/ls-VXH4QYF5.js +12 -0
- package/dist/chunks/mutate-OQWOKLIW.js +9 -0
- package/dist/chunks/notifications-KFZ333V5.js +7 -0
- package/dist/chunks/open-HH6K7ZRC.js +7 -0
- package/dist/chunks/openapi-JGYEFJJV.js +7 -0
- package/dist/chunks/permissions-ZSHKMXBZ.js +7 -0
- package/dist/chunks/pkg-EDJQLCNP.js +7 -0
- package/dist/chunks/plugin-offer-Z6FCPQFD.js +9 -0
- package/dist/chunks/prompt-missing-credentials-KOA7C4QC.js +7 -0
- package/dist/chunks/publish-FPNQ2US4.js +15 -0
- package/dist/chunks/pull-7OGOIKB3.js +7 -0
- package/dist/chunks/purchase-domain-if-available-F4LKHVBD.js +7 -0
- package/dist/chunks/push-NY3SIK2C.js +7 -0
- package/dist/chunks/query-JGPO7TNY.js +12 -0
- package/dist/chunks/reauthenticate-OZRQFR66.js +7 -0
- package/dist/chunks/reorder-4J2STFUS.js +10 -0
- package/dist/chunks/reply-EO4NTTPW.js +9 -0
- package/dist/chunks/repo-info-to-url-XQSULSEO.js +7 -0
- package/dist/chunks/resolve-RPHHRPNM.js +12 -0
- package/dist/chunks/resolve-agent-team-KX77HEAF.js +7 -0
- package/dist/chunks/resolve-deployment-framework-preset-AXXYBFCL.js +7 -0
- package/dist/chunks/restore-TEA6TSVK.js +16 -0
- package/dist/chunks/rm-BPILSPUI.js +8 -0
- package/dist/chunks/rm-F6XVUDBM.js +8 -0
- package/dist/chunks/rm-JCPXV2FN.js +8 -0
- package/dist/chunks/rm-LPQRGX7N.js +8 -0
- package/dist/chunks/rm-WHUGT6TE.js +8 -0
- package/dist/chunks/routes-P6LKQCWH.js +7 -0
- package/dist/chunks/rule-inspect-BOETGPFO.js +8 -0
- package/dist/chunks/schema-BEUO7G52.js +44 -0
- package/dist/chunks/schema-YOEAK4VX.js +14 -0
- package/dist/chunks/select-org-OMLGQEKK.js +7 -0
- package/dist/chunks/set-5XY27S7R.js +7 -0
- package/dist/chunks/setup-and-link-A7M3QT52.js +7 -0
- package/dist/chunks/skills-4J2NC2QI.js +590 -0
- package/dist/chunks/slugify-NMMUASYK.js +7 -0
- package/dist/chunks/stamp-TKONNIJ5.js +7 -0
- package/dist/chunks/tags-ZXZQEXOV.js +7 -0
- package/dist/chunks/token-W6P2KNI5.js +7 -0
- package/dist/chunks/token-util-JDQI37VN.js +7 -0
- package/dist/chunks/types-SK6J2HFE.js +14 -0
- package/dist/chunks/update-25CKNOY5.js +8 -0
- package/dist/chunks/update-route-version-KWK5S4UW.js +7 -0
- package/dist/chunks/utils-IQZEE4DT.js +86 -0
- package/dist/chunks/vlt-builder-graph-XL2XRO4V.js +7 -0
- package/dist/chunks/vlt-builder-importer-RBUPAB6J.js +11 -0
- package/dist/chunks/zod-2C2SXNIK.js +7 -0
- package/dist/commands/build/builder-worker.cjs +281 -0
- package/dist/commands/build/index.js +34 -0
- package/dist/commands/deploy/index.js +72 -0
- package/dist/commands/dev/builder-worker.cjs +110 -0
- package/dist/commands/dev/index.js +157 -0
- package/dist/commands/env/index.js +40 -0
- package/dist/commands/link/index.js +10 -0
- package/dist/commands/list/index.js +14 -0
- package/dist/commands/project/index.js +113 -0
- package/dist/commands-account.js +209 -0
- package/dist/commands-ai.js +200 -0
- package/dist/commands-blob.js +107 -0
- package/dist/commands-core.js +222 -0
- package/dist/commands-deployments.js +84 -0
- package/dist/commands-flags.js +377 -0
- package/dist/commands-integrations.js +143 -0
- package/dist/commands-observability.js +122 -0
- package/dist/commands-routing.js +273 -0
- package/dist/fetch-dist-tags.cjs +60 -0
- package/dist/get-latest-worker.cjs +222 -0
- package/dist/help.js +7 -0
- package/dist/index.js +25 -0
- package/dist/internal-build-worker.js +10 -0
- package/dist/internal-build.js +11 -0
- package/dist/package.json +265 -0
- package/dist/root-help-commands.mjs +1 -0
- package/dist/runtime-assets/dev-tunnel/api/tunnel.ts +443 -0
- package/dist/runtime-assets/dev-tunnel/lib/env.ts +25 -0
- package/dist/runtime-assets/dev-tunnel/lib/tunnel_pb.ts +505 -0
- package/dist/runtime-assets/node-preloads/next-dev-websocket.cjs +220 -0
- package/dist/vc.js +393 -0
- package/dist/version.mjs +2 -0
- package/package.json +224 -14
- package/index.js +0 -1
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{allOption,confirmOption,formatOption,jsonOption,limitOption,nextCursorOption,yesOption}from"./chunk-AWMQGOS2.js";import{packageName}from"./chunk-JESNVRVR.js";var listCommand={name:"list",aliases:["ls"],description:"List deployments.",arguments:[{name:"app",required:!1}],options:[allOption,{name:"meta",description:"Filter deployments by metadata (e.g.: `-m KEY=value`). Can appear many times.",argument:"KEY=VALUE",shorthand:null,deprecatedShorthand:"m",type:[String],deprecated:!1},{name:"policy",description:"See deployments with provided Deployment Retention policies (e.g.: `-p KEY=value`). Can appear many times.",argument:"KEY=VALUE",shorthand:null,deprecatedShorthand:"p",type:[String],deprecated:!1},{name:"environment",description:"Filter deployments by environment",argument:"ENVIRONMENT",shorthand:"e",type:String,deprecated:!1},{name:"status",description:"Filter deployments by their status. Can be comma-separated for multiple statuses (e.g.: `--status BUILDING,READY`)",argument:"STATUS",shorthand:null,deprecatedShorthand:"s",type:String,deprecated:!1},nextCursorOption,limitOption,{name:"prod",shorthand:null,type:Boolean,deprecated:!0},yesOption,confirmOption,formatOption,jsonOption],examples:[{name:"List all deployments for the currently linked project",value:`${packageName} list`},{name:"List all deployments across all projects",value:`${packageName} list --all`},{name:"List all deployments for the project `my-app`",value:`${packageName} list my-app`},{name:"Filter deployments by metadata",value:`${packageName} list --meta key1=value1 --meta key2=value2`},{name:"Paginate deployments for a project, where `1584722256178` is the time in milliseconds since the UNIX epoch",value:`${packageName} list my-app --next <CURSOR>`},{name:"Filter deployments by status",value:`${packageName} list --status READY`},{name:"Filter deployments by multiple statuses",value:`${packageName} list --status BUILDING,ERROR`}]};export{listCommand};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{getProductionUrl}from"./chunk-VT6RIZJH.js";import{require_dist as require_dist3}from"./chunk-ZH6KHD55.js";import{isDeploying}from"./chunk-ZFRNVIHI.js";import{events_default}from"./chunk-UJSW56GS.js";import{suggestNextCommands}from"./chunk-ANMDN3EG.js";import{getOrCreateDeploymentProtectionToken}from"./chunk-F2SWJEYV.js";import{progress}from"./chunk-U56NHYAH.js";import{deprecatedArchiveSplitTgz}from"./chunk-TPNOSQZ3.js";import{responseError}from"./chunk-G4T7VBGN.js";import{require_strip_ansi}from"./chunk-BS32OUOC.js";import{TelemetryClient}from"./chunk-2PKEEQ5W.js";import{require_ms}from"./chunk-MXTC4ZAQ.js";import{withGlobalFlags}from"./chunk-DGYHWXD2.js";import{getProjectByNameOrId,isJSONObject,printIndications,require_dist as require_dist2,require_types,sleep,ua_default}from"./chunk-KNLGWGUE.js";import{printAlignedLabel}from"./chunk-ADLBLGT3.js";import{fetch,getFetchDispatcher}from"./chunk-FUX6LKNP.js";import{APIError,BuildError,ProjectNotFound,require_bytes}from"./chunk-6VH56CX2.js";import{emoji,eraseLines,link_default,output_manager_default,prependEmoji}from"./chunk-XP3FT56R.js";import{require_dist}from"./chunk-RM3ZDRYE.js";import{require_source}from"./chunk-NB2WLB3J.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);function printPrebuiltFilePathMapIgnoreWarning(message,telemetry){telemetry.trackPrebuiltFilePathMapWouldFailClosed();let[first="",...rest]=message.split(`
|
|
8
|
+
`);output_manager_default.print(`${import_chalk.default.yellow("!")} ${first}
|
|
9
|
+
`);for(let line of rest)output_manager_default.print(`${line&&!/^\s/.test(line)?` ${line}`:line}
|
|
10
|
+
`)}var import_types=__toESM(require_types(),1),DeployTelemetryClient=class extends TelemetryClient{trackCliArgumentProjectPath(projectPaths){projectPaths&&this.trackCliArgument({arg:"project-path",value:this.redactedValue})}trackCliOptionArchive(format){if(format){let allowedFormat=[...import_types.VALID_ARCHIVE_FORMATS,deprecatedArchiveSplitTgz].includes(format)?format:this.redactedValue;this.trackCliOption({option:"archive",value:allowedFormat})}}trackCliFlagTurbo(turbo){turbo&&this.trackCliFlag("turbo")}trackCliOptionBuildEnv(buildEnv){buildEnv&&buildEnv.length>0&&this.trackCliOption({option:"build-env",value:this.redactedValue})}trackCliOptionEnv(env){env&&env.length>0&&this.trackCliOption({option:"env",value:this.redactedValue})}trackCliOptionMeta(meta){meta&&meta.length>0&&this.trackCliOption({option:"meta",value:this.redactedValue})}trackCliOptionDeployment(deployment){deployment&&this.trackCliOption({option:"deployment",value:this.redactedValue})}trackCliOptionId(id){id&&this.trackCliOption({option:"id",value:this.redactedValue})}trackCliOptionName(name){name&&this.trackCliOption({option:"name",value:this.redactedValue})}trackCliOptionRegions(regions){regions&&this.trackCliOption({option:"regions",value:this.redactedValue})}trackCliOptionTarget(target){target&&this.trackCliOption({option:"target",value:this.redactedTargetName(target)})}trackCliOptionEnvironment(environment){environment&&this.trackCliOption({option:"environment",value:this.redactedTargetName(environment)})}trackCliFlagConfirm(flag){flag&&this.trackCliFlag("confirm")}trackCliFlagForce(flag){flag&&this.trackCliFlag("force")}trackCliFlagLogs(flag){flag&&this.trackCliFlag("logs")}trackCliFlagNoLogs(flag){flag&&this.trackCliFlag("no-logs")}trackCliFlagGuidance(flag){flag&&this.trackCliFlag("guidance")}trackCliFlagNoClipboard(flag){flag&&this.trackCliFlag("no-clipboard")}trackCliFlagNoWait(flag){flag&&this.trackCliFlag("no-wait")}trackCliFlagDry(flag){flag&&this.trackCliFlag("dry")}trackCliFlagCreateIfMissing(flag){flag&&this.trackCliFlag("create-if-missing")}trackCliFlagVerify(flag){flag&&this.trackCliFlag("verify")}trackCliFlagPrebuilt(flag){flag&&this.trackCliFlag("prebuilt")}trackCliSubcommandInit(actual){this.trackCliSubcommand({subcommand:"init",value:actual})}trackCliSubcommandContinue(actual){this.trackCliSubcommand({subcommand:"continue",value:actual})}trackCliSubcommandDescribe(actual){this.trackCliSubcommand({subcommand:"describe",value:actual})}trackCliFlagProd(flag){flag&&this.trackCliFlag("prod")}trackCliFlagTemporary(flag){flag&&this.trackCliFlag("temporary")}trackTargetEnvironment(target){super.trackTargetEnvironment(target==="production"?"production":"preview")}trackCliFlagPublic(flag){flag&&this.trackCliFlag("public")}trackCliFlagSkipDomain(flag){flag&&this.trackCliFlag("skip-domain")}trackCliFlagWithCache(flag){flag&&this.trackCliFlag("with-cache")}trackCliFlagYes(flag){flag&&this.trackCliFlag("yes")}trackCliFlagJson(flag){flag&&this.trackCliFlag("json")}trackCliOptionFormat(format){format&&this.trackCliOption({option:"format",value:format})}trackDeploymentId(id){id&&this.trackCommandOutput({key:"deployment-id",value:id})}trackPrebuiltFilePathMapWouldFailClosed(){this.trackCommandOutput({key:"prebuilt-filepathmap-would-fail-closed",value:"TRUE"})}};var import_client=__toESM(require_dist3(),1),import_error_utils=__toESM(require_dist(),1),import_bytes=__toESM(require_bytes(),1),import_chalk2=__toESM(require_source(),1);function printInspectUrl(inspectorUrl){inspectorUrl&&printAlignedLabel("Inspect",import_chalk2.default.cyan(inspectorUrl))}async function processDeployment({org,projectName,isSettingUpProject,archive,skipAutoDetectionConfirmation,noWait,withFullLogs,anonymous,manual,jsonOutput,linkedProject,linkedProjectIsPartial,gitMetadata,...args}){let{now,path,requestBody,force,withCache,quiet,prebuilt,vercelOutputDir,rootDirectory,bulkRedirectsPath}=args,client=now._client,telemetry=new DeployTelemetryClient({opts:{store:client.telemetryEventStore}}),aliasedRowWillPrint=!noWait&&requestBody.autoAssignCustomDomains!==!1,{env={}}=requestBody;await client.ensureAuthorized();let token=now._token;if(!token)throw new Error("Missing authentication token");let aliasAssignedController=new AbortController,onAliasAssigned=event=>{aliasAssignedController.abort(event)},clientOptions={teamId:now.currentTeam??void 0,apiUrl:now._apiUrl,token,debug:output_manager_default.isDebugEnabled(),userAgent:ua_default,path,force,withCache,prebuilt,vercelOutputDir,rootDirectory,skipAutoDetectionConfirmation,archive,dispatcher:getFetchDispatcher(),projectName,bulkRedirectsPath,manual,aliasAssignedSignal:aliasAssignedController.signal},deployingSpinnerVal=isSettingUpProject?"Setting up project":`Deploying ${import_chalk2.default.bold(org.slug?`${org.slug}/${projectName}`:projectName)}`;output_manager_default.spinner(deployingSpinnerVal,0);let indications=[],prebuiltFilePathMapWarning,attachPrebuiltFilePathMapWarning=payload=>(prebuiltFilePathMapWarning&&Object.assign(payload,{warning:prebuiltFilePathMapWarning}),payload),abortController;function stopSpinner(){abortController?.abort(),output_manager_default.stopSpinner()}let linkedProjectLookup=linkedProjectIsPartial&&linkedProject&&!noWait?getProjectByNameOrId(client,linkedProject.id,linkedProject.accountId).then(project2=>({project:project2}),error=>({error})):void 0,rollingRelease=linkedProject?.rollingRelease,project=linkedProjectLookup?void 0:linkedProject,latestLogMessage="";async function resolveProject(){if(!linkedProjectLookup)return getProjectByNameOrId(client,projectName);let result=await linkedProjectLookup;if("error"in result)throw result.error;return result.project}try{let deploymentOptions=Promise.resolve(gitMetadata).then(gitMetadata2=>({...requestBody,...gitMetadata2===void 0?{}:{gitMetadata:gitMetadata2}}));for await(let event of(0,import_client.createDeployment)(clientOptions,deploymentOptions)){if(event.type==="warning"&&"code"in event&&event.code==="PREBUILT_FILEPATHMAP_IGNORED"){let message=String(event.payload);prebuiltFilePathMapWarning={code:"PREBUILT_FILEPATHMAP_IGNORED",message},printPrebuiltFilePathMapIgnoreWarning(message,telemetry),client.stderr.isTTY&&output_manager_default.spinner(deployingSpinnerVal,0);continue}if(["tip","notice","warning"].includes(event.type)&&indications.push(event),event.type==="file-count"){let{total,missing,uploads}=event.payload;output_manager_default.debug(`Total files ${total.size}, ${missing.length} changed`);let missingSize=missing.map(sha=>{let file=total.get(sha);return file?.data?.length??file?.size??0}).reduce((a,b)=>a+b,0),totalSizeHuman=import_bytes.default.format(missingSize,{decimalPlaces:1}),nextStep=0,stepSize=now._client.stderr.isTTY?0:.25,updateProgress=()=>{let uploadedBytes=uploads.reduce((acc,e)=>acc+e.bytesUploaded,0),bar=progress(uploadedBytes,missingSize);if(!bar)output_manager_default.spinner(deployingSpinnerVal,0);else{let uploadedHuman=import_bytes.default.format(uploadedBytes,{decimalPlaces:1,fixedDecimals:!0});uploadedBytes/missingSize>=nextStep&&(output_manager_default.spinner(`Uploading ${import_chalk2.default.reset(`[${bar}] (${uploadedHuman}/${totalSizeHuman})`)}`,0),nextStep+=stepSize)}};uploads.forEach(e=>e.on("progress",updateProgress)),updateProgress()}if(event.type==="file-uploaded"){let{file}=event.payload;output_manager_default.debug(`Uploaded: ${file.names.join(" ")} (${(0,import_bytes.default)(file.data?.length??file.size??0)})`)}if(event.type==="created"){let deployment=event.payload;if(now.url=deployment.url,stopSpinner(),!anonymous){printInspectUrl(deployment.inspectorUrl);let isProdDeployment=deployment.target==="production",previewUrl=`https://${deployment.url}`;isProdDeployment&&!requestBody.target&&indications.push({type:"notice",payload:"This is your project\u2019s first deployment, so it was assigned to production. Future deployments will be preview deployments unless you use --prod.",link:"https://vercel.com/docs/deployments/environments"}),printAlignedLabel(isProdDeployment?"Production":"Preview",import_chalk2.default.cyan(previewUrl),isProdDeployment&&!aliasedRowWillPrint?{gutter:"\u25B2"}:{}),!jsonOutput&&(quiet||process.env.FORCE_TTY==="1")&&process.stdout.write(`https://${event.payload.url}`)}if(noWait)return deployment.indications=indications,attachPrebuiltFilePathMapWarning(deployment);if(latestLogMessage=deployment.readyState==="QUEUED"?"Queued\u2026":"Building\u2026",withFullLogs&&!anonymous){let{displayBuildLogs}=await import("./logs-UD7FEXZ7.js"),promise;({abortController,promise}=displayBuildLogs(client,deployment,!0,onAliasAssigned)),promise.catch(error=>output_manager_default.warn(`Failed to read build logs: ${error}`))}else if(!anonymous){let{parseLogLines}=await import("./logs-UD7FEXZ7.js");abortController=new AbortController,events_default(client,deployment.id,{mode:"logs",onAliasAssigned,onEvent:event2=>{if(!event2.created)return;let message=parseLogLines(event2)[0];message&&(latestLogMessage=message,output_manager_default.spinner(latestLogMessage,0))},quiet:!1,findOpts:{direction:"forward",follow:!0}},abortController).catch(error=>output_manager_default.warn(`Failed to read build logs: ${error}`))}output_manager_default.spinner(latestLogMessage,0)}if(event.type==="building"&&!withFullLogs&&output_manager_default.spinner(latestLogMessage||"Building\u2026",0),event.type==="canceled")return stopSpinner(),attachPrebuiltFilePathMapWarning(event.payload);if(project===void 0&&(!linkedProjectLookup||event.type==="ready")&&(project=await resolveProject(),rollingRelease=project?.rollingRelease),event.type==="ready"&&rollingRelease)return output_manager_default.spinner("Releasing\u2026",0),stopSpinner(),event.payload.indications=indications,attachPrebuiltFilePathMapWarning(event.payload);if(event.type==="ready"&&!withFullLogs){let v1ChecksPending=event.payload.checksState&&event.payload.checksState!=="completed",v2ChecksPending=event.payload.checks?.["deployment-alias"]?.state==="pending";if(output_manager_default.stopSpinner(),!anonymous&&!output_manager_default.spinnersHidden){process.stderr.write(eraseLines(2));let isProdDeployment=event.payload.target==="production",previewUrl=`https://${event.payload.url}`;printAlignedLabel(isProdDeployment?"Production":"Preview",import_chalk2.default.cyan(previewUrl),isProdDeployment&&!aliasedRowWillPrint?{gutter:"\u25B2"}:{})}v1ChecksPending||v2ChecksPending?output_manager_default.spinner("Running Checks\u2026",0):output_manager_default.spinner("Completing\u2026",0)}if(event.type==="checks-running"&&!withFullLogs&&output_manager_default.spinner("Running Checks\u2026",0),event.type==="checks-conclusion-failed"||event.type==="checks-v2-failed")return stopSpinner(),attachPrebuiltFilePathMapWarning(event.payload);if(event.type==="error"){if(stopSpinner(),!archive){let maybeError=handleErrorSolvableWithArchive(event.payload);if(maybeError)throw maybeError}let error=await now.handleDeploymentError(event.payload,{env});if(error.code==="missing_project_settings"||error.code==="forbidden")return error;throw error}if(event.type==="alias-assigned"){if(stopSpinner(),event.payload.target==="production"&&event.payload.alias&&event.payload.alias.length>0){let prodUrl=`https://${event.payload.alias[0]}`;anonymous&&output_manager_default.print(`
|
|
11
|
+
`),printAlignedLabel(anonymous?"Temporary":"Aliased",import_chalk2.default.cyan(prodUrl),{gutter:"\u25B2"}),anonymous&&!jsonOutput&&(quiet||process.env.FORCE_TTY==="1")&&process.stdout.write(prodUrl)}return event.payload.indications=indications,attachPrebuiltFilePathMapWarning(event.payload)}}}catch(err){throw stopSpinner(),err}}var archiveSuggestionText="Try using `--archive=tgz` to limit the amount of files you upload.",UploadErrorMissingArchive=class extends Error{constructor(){super(...arguments);this.link="https://vercel.com/docs/cli/deploy#archive"}};function handleErrorSolvableWithArchive(error){if((0,import_error_utils.isErrorLike)(error)){let isUploadRateLimit="errorName"in error&&typeof error.errorName=="string"&&error.errorName.startsWith("api-upload-"),isTooManyFilesLimit="code"in error&&error.code==="too_many_files",isEntityTooLarge=/entity too large|payload too large/i.test(error.message);if(isUploadRateLimit||isTooManyFilesLimit||isEntityTooLarge)return new UploadErrorMissingArchive(`${error.message}
|
|
12
|
+
${archiveSuggestionText}`)}}var import_async_retry=__toESM(require_dist2(),1),import_ms=__toESM(require_ms(),1);import qs from"querystring";import{parse as parseUrl}from"url";var import_bytes2=__toESM(require_bytes(),1),import_chalk3=__toESM(require_source(),1);var Now=class{constructor({client,url=null,currentTeam=null,forceNew=!1,withCache=!1}){this.url=url,this._client=client,this._forceNew=forceNew,this._withCache=withCache,this._onRetry=this._onRetry.bind(this),this.currentTeam=currentTeam}get _apiUrl(){return this._client.apiUrl}get _token(){return this._client.authConfig.token}async create(path,{nowConfig={},name,project,prebuilt=!1,anonymous=!1,vercelOutputDir,rootDirectory,meta,gitMetadata,regions,quiet=!1,env,build,buildMachine,forceNew=!1,withCache=!1,target=null,projectSettings,skipAutoDetectionConfirmation,noWait,withFullLogs,autoAssignCustomDomains,agentName,manual,jsonOutput=!1,linkedProject,linkedProjectIsPartial},org,isSettingUpProject,archive){let requestBody={...nowConfig,env,build,buildMachine,name,project,meta,regions,target:target||void 0,projectSettings,source:"cli",actor:agentName,autoAssignCustomDomains};delete requestBody.scope,delete requestBody.github,delete requestBody.public;let deployment=await processDeployment({now:this,path,requestBody,gitMetadata,quiet,force:forceNew,withCache,org,projectName:name,isSettingUpProject,archive,skipAutoDetectionConfirmation,prebuilt,anonymous,vercelOutputDir,rootDirectory,noWait,withFullLogs,bulkRedirectsPath:nowConfig.bulkRedirectsPath,manual,jsonOutput,linkedProject,linkedProjectIsPartial});if(deployment&&deployment.warnings){let sizeExceeded=0,{log,warn}=output_manager_default;deployment.warnings.forEach(warning=>{if(warning.reason==="size_limit_exceeded"){let{sha,limit}=warning;warn(`Skipping file ${sha} (size exceeded ${(0,import_bytes2.default)(limit)})`),sizeExceeded++}else warning.reason==="node_version_not_found"&&warn(`Requested node version ${warning.wanted} is not available`)}),sizeExceeded>0&&(warn(`${sizeExceeded} of the files exceeded the limit for your plan.`),log(`Please upgrade your plan here: ${import_chalk3.default.cyan("https://vercel.com/account/plan")}`))}return deployment}async handleDeploymentError(error,{env}){if(error.status===429){if(error.code==="builds_rate_limited"){let err2=new Error(error.message);return err2.status=error.status,err2.code=error.code,err2.retryAfterMs="never",err2.ctaLabel=error.ctaLabel,err2.ctaUrl=error.ctaUrl,err2.action=error.action,err2.link=error.link,err2}let msg="You have been creating deployments at a very fast pace. ";if(error.limit&&error.limit.reset){let{reset}=error.limit,difference=reset-Date.now();msg+=`Please retry in ${(0,import_ms.default)(difference,{long:!0})}.`}else msg+="Please slow down.";let err=Object.create(APIError.prototype);return err.message=msg,err.status=error.status,err.retryAfterMs="never",err}if(error.status===400&&error.code==="cert_missing")return responseError(error,null,error);if(error.status===400&&error.code==="missing_files")return this._missing=error.missing||[],error;if(error.status===404&&error.code==="not_found")return error;if(error.status>=400&&error.status<500){let err=new Error,{code}=error;if(code==="env_value_invalid_type"){let{key}=error;err.message=`The env key ${key} has an invalid type: ${typeof env[key]}. Please supply a String or a Number (https://err.sh/vercel/env-value-invalid-type)`}else Object.assign(err,error);return err}return error.id&&error.id.startsWith("bld_")?new BuildError({message:"Build failed",meta:{entrypoint:error.entrypoint}}):error.errorCode==="BUILD_FAILED"||error.errorCode==="UNEXPECTED_ERROR"||error.errorCode?.includes("BUILD_UTILS_SPAWN_")?new BuildError({message:error.errorMessage,meta:{}}):new Error(error.message||error.errorMessage)}async remove(deploymentId,{hard=!1}){let url=`/now/deployments/${deploymentId}?hard=${hard?1:0}`;return await this.retry(async bail=>{let res=await this._fetch(url,{method:"DELETE"});if(res.status!==200){let error=await responseError(res,"Failed to remove deployment");if(typeof error.retryAfterMs=="number"){let randomSkewMs=3e4*Math.random();throw await sleep(error.retryAfterMs+randomSkewMs),error}if(res.status>200&&res.status<500)return bail(error);throw error}}),!0}retry(fn,{retries=3,maxTimeout=1/0}={}){return(0,import_async_retry.default)(fn,{retries,maxTimeout,onRetry:this._onRetry})}_onRetry(err){output_manager_default.debug(`Retrying: ${err}
|
|
13
|
+
${err.stack}`)}async _fetch(_url,opts={}){if(opts.useCurrentTeam!==!1&&this.currentTeam){let parsedUrl=parseUrl(_url,!0),query=parsedUrl.query;query.teamId=this.currentTeam,_url=`${parsedUrl.pathname}?${qs.stringify(query)}`,delete opts.useCurrentTeam}opts.headers=new globalThis.Headers(opts.headers),opts.headers.set("accept","application/json"),this._token&&opts.headers.set("authorization",`Bearer ${this._token}`),opts.headers.set("user-agent",ua_default);let body;isJSONObject(opts.body)?(body=JSON.stringify(opts.body),opts.headers.set("content-type","application/json; charset=utf8")):body=opts.body;let res=await output_manager_default.time(`${opts.method||"GET"} ${this._apiUrl}${_url} ${opts.body||""}`,fetch(`${this._apiUrl}${_url}`,{...opts,body}));return printIndications(res),res}async fetch(url,opts={}){return this.retry(async bail=>{opts.json!==!1&&opts.body&&typeof opts.body=="object"&&(opts=Object.assign({},opts,{body:JSON.stringify(opts.body),headers:Object.assign({},opts.headers,{"Content-Type":"application/json"})}));let res=await this._fetch(url,opts);if(res.ok)return opts.json===!1?res:res.headers.get("content-type")?res.headers.get("content-type")?.includes("application/json")?res.json():res:null;let err=await responseError(res);if(typeof err.retryAfterMs=="number"){let randomSkewMs=3e4*Math.random();throw await sleep(err.retryAfterMs+randomSkewMs),err}if(res.status>=400&&res.status<500)return bail(err);throw err},opts.retry)}};var import_bytes3=__toESM(require_bytes(),1),import_strip_ansi=__toESM(require_strip_ansi(),1),import_error_utils2=__toESM(require_dist(),1);var TIMEOUT_MS=3e4,MAX_REDIRECTS=5,REDIRECT_STATUSES=new Set([301,302,303,307,308]),TITLE_SEARCH_LENGTH=64*1024,TITLE_MAX_LENGTH=200;async function verifyDeployment(client,url,{project,org,protectionEnabled}){try{let res=await request(url);if((res.status===401||res.status===403)&&protectionEnabled&&project&&org){let bypassToken=await getBypassToken(client,project,org);bypassToken&&(await res.body?.cancel(),res=await request(url,bypassToken))}return await readVerification(url,res)}catch(err){let cause=err instanceof Error&&err.cause instanceof Error?`: ${err.cause.message}`:"";return{url,ok:!1,statusCode:null,size:null,title:null,error:`${(0,import_error_utils2.errorToString)(err)}${cause}`}}}async function request(url,bypassToken){let deploymentOrigin=new URL(url).origin,signal=AbortSignal.timeout(TIMEOUT_MS),current=url;for(let redirects=0;;redirects++){let headers={};bypassToken&&new URL(current).origin===deploymentOrigin&&(headers["x-vercel-protection-bypass"]=bypassToken);let res=await fetch(current,{headers,redirect:"manual",signal}),location=res.headers.get("location");if(!REDIRECT_STATUSES.has(res.status)||!location)return res;if(await res.body?.cancel(),redirects===MAX_REDIRECTS)throw new Error(`Too many redirects (more than ${MAX_REDIRECTS})`);current=new URL(location,current).href}}async function getBypassToken(client,{id,accountId},org){try{let project=await getProjectByNameOrId(client,id,accountId);return project instanceof ProjectNotFound?null:await getOrCreateDeploymentProtectionToken(client,{status:"linked",project,org})}catch(err){return output_manager_default.debug(`Could not get a protection bypass secret: ${err}`),null}}async function readVerification(url,res){let isHtml=(res.headers.get("content-type")??"").includes("text/html"),decoder=new TextDecoder,size=0,head="",reader=res.body?.getReader();if(reader)for(;;){let{done,value}=await reader.read();if(done)break;size+=value.byteLength,isHtml&&head.length<TITLE_SEARCH_LENGTH&&(head+=decoder.decode(value,{stream:!0}))}return{url,ok:res.ok,statusCode:res.status,size,title:isHtml?parseTitle(head):null,error:null}}function formatVerificationSummary({statusCode,size,title}){return[statusCode,size===null?null:import_bytes3.default.format(size,{decimalPlaces:1,unitSeparator:" "}),title===null?null:`"${title}"`].filter(part=>part!==null).join(", ")}function formatVerificationFailure({url,statusCode,error}){return statusCode===null?`Couldn't load ${url}: ${error}`:`${url} returned ${statusCode}.`}var HTML_ENTITIES={"&":"&","<":"<",">":">",""":'"',"'":"'","'":"'"};function parseTitle(html){let match=/<title[^>]*>([\s\S]*?)<\/title>/i.exec(html);if(!match)return null;let title=Array.from((0,import_strip_ansi.default)(match[1]).replace(/&(?:amp|lt|gt|quot|#39|#x27);/g,entity=>HTML_ENTITIES[entity])).map(char=>char<" "||char==="\x7F"?" ":char).join("").replace(/\s+/g," ").trim();return title?title.slice(0,TITLE_MAX_LENGTH):null}var import_chalk4=__toESM(require_source(),1),import_strip_ansi2=__toESM(require_strip_ansi(),1);function bareDuration(stamp){return(0,import_strip_ansi2.default)(stamp).replace(/^\[|\]$/g,"")}async function printDeploymentStatus(client,{readyState,alias,aliasAssigned,aliasError,indications,aliasWarning,url,target},deployStamp,noWait,guidanceMode,isInit,gitConnectCommand,protectionNames,verification){indications=indications||[];let isStillBuilding=!1;if(noWait&&isDeploying(readyState)){isStillBuilding=!0;let message=isInit?"Deployment is awaiting continuation\u2026":"Note: Deployment is still processing\u2026";output_manager_default.print(prependEmoji(message,emoji("notice"))+`
|
|
14
|
+
`)}if(!isStillBuilding&&readyState!=="READY")return output_manager_default.error("Your deployment failed. Please retry later. More: https://err.sh/vercel/deployment-error"),1;if(!isStillBuilding&&readyState==="READY"){let duration=bareDuration(deployStamp());output_manager_default.print(`
|
|
15
|
+
${import_chalk4.default.green("\u2713")} ${import_chalk4.default.bold("Ready")} ${import_chalk4.default.dim(`in ${duration}`)}
|
|
16
|
+
`)}verification?.ok?output_manager_default.print(`${import_chalk4.default.green("\u2713")} ${import_chalk4.default.bold("Verified")} ${verification.url} ${import_chalk4.default.dim(`(${formatVerificationSummary(verification)})`)}
|
|
17
|
+
`):verification&&output_manager_default.error(formatVerificationFailure(verification)),protectionNames?.length&&output_manager_default.print(`
|
|
18
|
+
${import_chalk4.default.yellow("!")} Deployment Protection is on for this project (${protectionNames.join(", ")}). Use ${import_chalk4.default.cyan("`vercel curl`")} to access it.
|
|
19
|
+
`),aliasError&&output_manager_default.warn(`Failed to assign aliases${aliasError.message?`: ${aliasError.message}`:""}`),aliasWarning?.message&&indications.push({type:"warning",payload:aliasWarning.message,link:aliasWarning.link,action:aliasWarning.action});let newline=`
|
|
20
|
+
`;for(let indication of indications){let message=prependEmoji(import_chalk4.default.dim(indication.payload),emoji(indication.type))+newline,link="";indication.link&&(link=import_chalk4.default.dim(`${indication.action||"Learn More"}: ${link_default(indication.link)}`)+newline),output_manager_default.print(message+link)}if(gitConnectCommand||guidanceMode){output_manager_default.print(`
|
|
21
|
+
`);let nextCommands=[];if(gitConnectCommand&&nextCommands.push({description:"Automatically deploy changes on every push by connecting Git",command:gitConnectCommand}),readyState==="READY"){let productionUrl=getProductionUrl({target,alias,aliasAssigned,aliasError});verification?.ok||nextCommands.push({description:productionUrl?"Check the production response":"Check the deployment response",command:withGlobalFlags(client,`curl ${productionUrl??`https://${url}`}`,{preserveProject:!0})}),nextCommands.push({description:"View build logs",command:withGlobalFlags(client,`inspect ${url} --logs`,{preserveProject:!0})},{description:"Create a new deployment from the same source",command:withGlobalFlags(client,`redeploy ${url}`,{preserveProject:!0})}),target!=="production"&&nextCommands.push({description:"Deploy the current project to production",command:withGlobalFlags(client,"deploy --prod",{preserveProject:!0})})}else nextCommands.push({description:"Check deployment status",command:withGlobalFlags(client,`inspect ${url}`,{preserveProject:!0})});suggestNextCommands(nextCommands)}return verification&&!verification.ok?1:0}export{printPrebuiltFilePathMapIgnoreWarning,DeployTelemetryClient,UploadErrorMissingArchive,Now,verifyDeployment,formatVerificationFailure,printDeploymentStatus};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{__commonJS,__require,__toESM}from"./chunk-BZENIQ7N.js";var require_dist=__commonJS({"../../internals/get-package-json/dist/index.js"(exports,module){"use strict";var __create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toESM2=(mod,isNodeMode,target)=>(target=mod!=null?__create(__getProtoOf(mod)):{},__copyProps(isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target,mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),src_exports={};__export(src_exports,{getPackageJSON:()=>getPackageJSON2});module.exports=__toCommonJS(src_exports);var import_fs=__toESM2(__require("fs")),import_path=__toESM2(__require("path")),import_url=__require("url"),cache=new Map;function getPackageJSONPath(dir){return import_path.default.join(dir,"package.json")}function captureCallerCallSite(){let _prepareStackTrace=Error.prepareStackTrace,callSite;try{Error.prepareStackTrace=(_,stack)=>stack,callSite=new Error().stack[2]}finally{Error.prepareStackTrace=_prepareStackTrace}return callSite}function getPackageJSON2(){let callSite=captureCallerCallSite(),filePath=callSite.getFileName()||callSite.getEvalOrigin();filePath.startsWith("file://")&&(filePath=(0,import_url.fileURLToPath)(filePath));let rootDir=import_path.default.dirname(filePath),packageJSONPath=getPackageJSONPath(rootDir);for(;!import_fs.default.existsSync(packageJSONPath);)rootDir=import_path.default.join(rootDir,".."),packageJSONPath=getPackageJSONPath(rootDir);let packageJSON=cache.get(packageJSONPath);return packageJSON||(packageJSON=JSON.parse(import_fs.default.readFileSync(packageJSONPath,"utf-8")),cache.set(packageJSONPath,packageJSON)),packageJSON}}});var import_get_package_json=__toESM(require_dist(),1),pkg_default=(0,import_get_package_json.getPackageJSON)();export{pkg_default};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{__commonJS,__require}from"./chunk-BZENIQ7N.js";var require_windows=__commonJS({"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/windows.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs=__require("fs");function checkPathExt(path,options){var pathext=options.pathExt!==void 0?options.pathExt:process.env.PATHEXT;if(!pathext||(pathext=pathext.split(";"),pathext.indexOf("")!==-1))return!0;for(var i=0;i<pathext.length;i++){var p=pathext[i].toLowerCase();if(p&&path.substr(-p.length).toLowerCase()===p)return!0}return!1}function checkStat(stat,path,options){return!stat.isSymbolicLink()&&!stat.isFile()?!1:checkPathExt(path,options)}function isexe(path,options,cb){fs.stat(path,function(er,stat){cb(er,er?!1:checkStat(stat,path,options))})}function sync(path,options){return checkStat(fs.statSync(path),path,options)}}});var require_mode=__commonJS({"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/mode.js"(exports,module){module.exports=isexe;isexe.sync=sync;var fs=__require("fs");function isexe(path,options,cb){fs.stat(path,function(er,stat){cb(er,er?!1:checkStat(stat,options))})}function sync(path,options){return checkStat(fs.statSync(path),options)}function checkStat(stat,options){return stat.isFile()&&checkMode(stat,options)}function checkMode(stat,options){var mod=stat.mode,uid=stat.uid,gid=stat.gid,myUid=options.uid!==void 0?options.uid:process.getuid&&process.getuid(),myGid=options.gid!==void 0?options.gid:process.getgid&&process.getgid(),u=parseInt("100",8),g=parseInt("010",8),o=parseInt("001",8),ug=u|g,ret=mod&o||mod&g&&gid===myGid||mod&u&&uid===myUid||mod&ug&&myUid===0;return ret}}});var require_isexe=__commonJS({"../../node_modules/.pnpm/isexe@2.0.0/node_modules/isexe/index.js"(exports,module){var fs=__require("fs"),core;process.platform==="win32"||global.TESTING_WINDOWS?core=require_windows():core=require_mode();module.exports=isexe;isexe.sync=sync;function isexe(path,options,cb){if(typeof options=="function"&&(cb=options,options={}),!cb){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(resolve,reject){isexe(path,options||{},function(er,is){er?reject(er):resolve(is)})})}core(path,options||{},function(er,is){er&&(er.code==="EACCES"||options&&options.ignoreErrors)&&(er=null,is=!1),cb(er,is)})}function sync(path,options){try{return core.sync(path,options||{})}catch(er){if(options&&options.ignoreErrors||er.code==="EACCES")return!1;throw er}}}});export{require_isexe};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{printProjectNotFoundError}from"./chunk-BL3HBRF6.js";import{param}from"./chunk-3G3FQYMW.js";import{detectExplicitScope}from"./chunk-B4UE4LVE.js";import{AGENT_REASON,AGENT_STATUS,buildCommandWithYes,outputActionRequired,outputAgentError}from"./chunk-DGYHWXD2.js";import{getLinkedProject,resolveProjectCwd}from"./chunk-KNLGWGUE.js";import{getCommandName,getCommandNamePlain}from"./chunk-JESNVRVR.js";import{output_manager_default,require_build_utils}from"./chunk-XP3FT56R.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_build_utils=__toESM(require_build_utils(),1);async function ensureLink(commandName,client,cwd,opts={}){opts.singleFile||(cwd=await resolveProjectCwd(cwd));let link=opts.link,nonInteractive=opts.nonInteractive??client.nonInteractive??!1;if(opts.nonInteractive=nonInteractive,link||(opts.forceDelete?link={status:"not_linked",org:null,project:null}:link=await getLinkedProject(client,{cwd,projectName:opts.projectName,projectNameIsExplicit:!!(opts.projectName&&opts.failIfNotFound),scopeIsExplicit:detectExplicitScope(client),allowOwnerLookupFallback:opts.allowOwnerLookupFallback,skipOwnerLookup:opts.skipOwnerLookup,skipRemoteLookup:opts.skipRemoteLookup,skipProjectRootResolution:!!opts.singleFile}),opts.link=link),link.status==="linked"&&opts.forceDelete||link.status==="not_linked"){if(link.status==="not_linked"&&opts.failIfNotFound&&opts.projectName){let pinnedProjectId=(0,import_build_utils.getPlatformEnv)("PROJECT_ID"),creatable=!opts.projectName.startsWith("prj_")&&!pinnedProjectId;if(!opts.createIfNotFound||opts.projectName.startsWith("prj_")||pinnedProjectId===opts.projectName)return await printProjectNotFoundError(client,opts.projectName,commandName,link.orgId,{createCommand:creatable?opts.createCommand:void 0}),1;if(pinnedProjectId){let message=`Can't use --project with VERCEL_PROJECT_ID. --project is "${opts.projectName}" and VERCEL_PROJECT_ID is "${pinnedProjectId}". Remove one of them.`,helpCommand=getCommandNamePlain(`${commandName} --help`);return output_manager_default.error(`${message}
|
|
8
|
+
|
|
9
|
+
See all options:
|
|
10
|
+
${helpCommand}`),outputAgentError(client,{status:AGENT_STATUS.ERROR,reason:AGENT_REASON.INVALID_ARGUMENTS,message,next:[{command:helpCommand,when:"see all options"}]}),2}}if(link.status==="not_linked"&&opts.requireExistingLink)return output_manager_default.error(`Project is not linked. Run ${getCommandName("link")} first.`),1;let{default:setupAndLink}=await import("./setup-and-link-A7M3QT52.js");if(link=await setupAndLink(client,cwd,opts),link.status==="not_linked")return 0}return link.status==="error"?(link.reason==="HEADLESS"&&(nonInteractive?outputActionRequired(client,{status:"action_required",reason:"confirmation_required",message:`Command ${getCommandNamePlain(commandName)} requires confirmation. Use option --yes to confirm.`,next:[{command:buildCommandWithYes(client.argv),when:"Confirm and run"}]},link.exitCode):output_manager_default.error(`Command ${getCommandName(commandName)} requires confirmation. Use option ${param("--yes")} to confirm.`)),nonInteractive&&process.exit(link.exitCode),link.exitCode):link}export{ensureLink};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{require_dist as require_dist2,validateConfig}from"./chunk-RUXO73ON.js";import{compileVercelConfig,findSourceVercelConfigFile}from"./chunk-7Y46LB43.js";import{applyEdits,findNodeAtLocation,init_main,modify,parse,parseTree}from"./chunk-J24BABG4.js";import{init_dist,stringify}from"./chunk-U4Z2MMOF.js";import{require_dist2 as require_dist}from"./chunk-7L2K4OKM.js";import{printAlignedLabel}from"./chunk-ADLBLGT3.js";import{code}from"./chunk-6VH56CX2.js";import{link_default,output_manager_default,require_build_utils}from"./chunk-XP3FT56R.js";import{require_source}from"./chunk-NB2WLB3J.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_chalk=__toESM(require_source(),1);init_main();init_dist();var import_build_utils=__toESM(require_build_utils(),1),import_fs_detectors=__toESM(require_dist(),1),import_service_topology=__toESM(require_dist2(),1);import{readFile,writeFile}from"fs/promises";import{basename}from"path";var EXPERIMENTAL_SERVICES_DOCS_URL="https://vercel.com/docs/services/experimental";async function prepareExperimentalServicesMigration(cwd,detectServicesResult){let compileResult=await compileVercelConfig(cwd);if(!compileResult.configPath)return null;let rawConfig=await readFile(compileResult.configPath,"utf8"),config=parse(rawConfig);if(!config||!(0,import_service_topology.hasLegacyServicesConfig)(config))return null;let resolvedServices=detectServicesResult?.resolved?.source==="configured"?detectServicesResult.services.filter(s=>(0,import_build_utils.isExperimentalService)(s)):void 0,plan=await(0,import_service_topology.migrateExperimentalServices)({fs:new import_fs_detectors.LocalFileSystemDetector(cwd),config,resolvedServices:resolvedServices&&resolvedServices.length>0?resolvedServices:void 0}),sourceFile=compileResult.sourceFile??basename(compileResult.configPath),preparation={plan,sourceFile,snippet:renderSnippet(sourceFile,plan)};if(plan.errors.length>0)return preparation;if(compileResult.wasCompiled)return preparation.writeBlocker=`${sourceFile} can't be updated automatically.`,preparation;let content=applyPlanToJson(rawConfig,config,plan),parseErrors=[],nextConfig=parse(content,parseErrors);if(parseErrors.length>0)return preparation.writeBlocker=`Couldn't produce a valid ${sourceFile}.`,preparation;let validationError=validateConfig(nextConfig);return validationError?(preparation.writeBlocker=validationError.message,preparation):(preparation.write={configPath:compileResult.configPath,content},preparation)}function applyPlanToJson(rawConfig,config,plan){let eol=rawConfig.includes(`\r
|
|
8
|
+
`)?`\r
|
|
9
|
+
`:`
|
|
10
|
+
`,indent2=/^([ \t]+)\S/m.exec(rawConfig)?.[1]??" ",formattingOptions={eol,insertSpaces:!indent2.startsWith(" "),tabSize:indent2.startsWith(" ")?1:indent2.length},legacyKey=config.experimentalServices?"experimentalServices":"experimentalServicesV2",key=findNodeAtLocation(parseTree(rawConfig),[legacyKey]).parent.children[0],text=applyEdits(rawConfig,[{offset:key.offset,length:key.length,content:'"services"'}]);text=applyEdits(text,modify(text,["services"],plan.patch.services,{formattingOptions}));for(let key2 of plan.removeKeys)key2!==legacyKey&&(text=applyEdits(text,modify(text,[key2],void 0,{formattingOptions})));for(let[key2,value]of Object.entries(plan.patch.build?.env??{}))text=applyEdits(text,modify(text,["build","env",key2],value,{formattingOptions}));if(plan.patch.rewrites.length>0)if(Array.isArray(config.rewrites))for(let rewrite of plan.patch.rewrites)text=applyEdits(text,modify(text,["rewrites",-1],rewrite,{formattingOptions}));else text=applyEdits(text,modify(text,["rewrites"],plan.patch.rewrites,{formattingOptions,getInsertionIndex:keys=>keys.indexOf("services")+1}));return text.endsWith(`
|
|
11
|
+
`)?text:`${text}${eol}`}function renderSnippet(sourceFile,plan){let patch={services:plan.patch.services};return plan.patch.rewrites.length>0&&(patch.rewrites=plan.patch.rewrites),plan.patch.build&&(patch.build=plan.patch.build),sourceFile==="vercel.toml"?stringify(patch).trimEnd():JSON.stringify(patch,null,2)}function displayExperimentalServicesMigration(preparation){let{plan,sourceFile,snippet}=preparation,legacyKey=plan.removeKeys.includes("experimentalServices")?"experimentalServices":"experimentalServicesV2";if(output_manager_default.print(`${import_chalk.default.yellow("!")} ${sourceFile} uses ${code(legacyKey)}, which is replaced by ${code("services")}. ${link_default(EXPERIMENTAL_SERVICES_DOCS_URL)}
|
|
12
|
+
`),plan.errors.length>0){output_manager_default.print(` ${import_chalk.default.bold(`Can't migrate ${sourceFile} automatically:`)}
|
|
13
|
+
`);for(let error of plan.errors)output_manager_default.print(` ${import_chalk.default.red("\u2717")} ${error.message}
|
|
14
|
+
`);return}output_manager_default.print(`
|
|
15
|
+
${import_chalk.default.bold(`Suggested ${sourceFile} configuration:`)}
|
|
16
|
+
`),output_manager_default.print(`${indent(snippet,2)}
|
|
17
|
+
`),plan.patch.build&&!preparation.write&&output_manager_default.print(" Merge these `build.env` defaults with any existing build settings.\n");let removed=plan.removeKeys.filter(k=>k!==legacyKey);removed.length>0&&output_manager_default.print(`
|
|
18
|
+
Also removes top-level ${removed.map(k=>code(k)).join(", ")}.
|
|
19
|
+
`);for(let rename of plan.renamedServices)output_manager_default.print(` Service ${code(rename.from)} is renamed to ${code(rename.to)}.
|
|
20
|
+
`);for(let[heading,notes]of[["Review before deploying:",plan.warnings],["Not migrated:",plan.unmigrated]])if(notes.length>0){output_manager_default.print(`
|
|
21
|
+
${import_chalk.default.bold(heading)}
|
|
22
|
+
`);for(let note of notes){let link=note.link?` ${link_default(note.link)}`:"";output_manager_default.print(`${import_chalk.default.yellow("!")} ${note.message}${link}
|
|
23
|
+
`)}}output_manager_default.print(`
|
|
24
|
+
`)}function indent(text,spaces){let pad=" ".repeat(spaces);return text.split(`
|
|
25
|
+
`).map(line=>`${pad}${line}`).join(`
|
|
26
|
+
`)}async function promptExperimentalServicesMigration({client,cwd,autoConfirm=!1,nonInteractive=!1,allowConfigExecution=!0,detectServicesResult}){let preparation;try{if(!allowConfigExecution){let sourceFile=await findSourceVercelConfigFile(cwd);if(sourceFile&&sourceFile!=="vercel.toml")return!1}preparation=await prepareExperimentalServicesMigration(cwd,detectServicesResult)}catch(error){return output_manager_default.debug(`Skipping services migration suggestion: ${error}`),!1}if(!preparation||(displayExperimentalServicesMigration(preparation),preparation.plan.errors.length>0))return!1;if(!preparation.write)return preparation.writeBlocker&&output_manager_default.print(` ${preparation.writeBlocker} Apply the configuration above to ${preparation.sourceFile} manually.
|
|
27
|
+
|
|
28
|
+
`),!1;let interactive=client.stdin.isTTY&&!nonInteractive,confirmed=autoConfirm;return!confirmed&&interactive&&(confirmed=await client.input.confirm(`Update ${preparation.sourceFile} with this configuration?`,!0)),confirmed?(await writeFile(preparation.write.configPath,preparation.write.content,"utf8"),printAlignedLabel("Updated",preparation.sourceFile,{gutter:"\u2713"}),preparation.plan.unmigrated.length>0&&output_manager_default.print(` ${preparation.plan.unmigrated.length} service${preparation.plan.unmigrated.length===1?" was":"s were"} left out. Migrate ${preparation.plan.unmigrated.length===1?"it":"them"} manually before deploying.
|
|
29
|
+
`),output_manager_default.print(`
|
|
30
|
+
`),!0):(!interactive&&!autoConfirm&&output_manager_default.print(` Run this command in a terminal to apply it, pass ${code("--yes")} to accept the migration, or update ${preparation.sourceFile} manually.
|
|
31
|
+
|
|
32
|
+
`),!1)}export{promptExperimentalServicesMigration};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{getEnvRecords,parseEnv,pullEnvRecords}from"./chunk-YN3C5BL5.js";import{require_frameworks}from"./chunk-6Y2ZL5XJ.js";import{parseTarget}from"./chunk-X4762EE4.js";import{require_json_parse_better_errors}from"./chunk-25565AGS.js";import{resolveProjectContext}from"./chunk-3JGBBS6V.js";import{getRenamedOption,renameOptionInArgs,reportRenamedOptionError}from"./chunk-IEPW2YRH.js";import{STANDARD_ENVIRONMENTS}from"./chunk-7YKFF6CE.js";import{formatProject}from"./chunk-6OVX3PWM.js";import{ensureLink}from"./chunk-OQCMRU3J.js";import{getDeployment}from"./chunk-R6BEOVTU.js";import{pullSubcommand}from"./chunk-LJBUJ23M.js";import{printError}from"./chunk-G4T7VBGN.js";import{param}from"./chunk-3G3FQYMW.js";import{TelemetryClient}from"./chunk-2PKEEQ5W.js";import{buildCommandWithYes,getPreservedArgsForEnvPull,outputActionRequired,outputAgentError}from"./chunk-DGYHWXD2.js";import{addToGitIgnore,require_lib}from"./chunk-KNLGWGUE.js";import{printAlignedLabel}from"./chunk-ADLBLGT3.js";import{parseArguments}from"./chunk-VOCZ34ON.js";import{getFlagsSpecification}from"./chunk-AWMQGOS2.js";import{getCommandName,getCommandNamePlain}from"./chunk-JESNVRVR.js";import{output_manager_default}from"./chunk-XP3FT56R.js";import{require_dist}from"./chunk-RM3ZDRYE.js";import{require_source}from"./chunk-NB2WLB3J.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_chalk2=__toESM(require_source(),1),import_fs_extra2=__toESM(require_lib(),1);import{closeSync,openSync,readSync}from"fs";import{resolve}from"path";var import_fs_extra=__toESM(require_lib(),1);var import_chalk=__toESM(require_source(),1);async function createEnvObject(envPath){let envArr=(await(0,import_fs_extra.readFile)(envPath,"utf-8")).replace(/"/g,"").split(/\r?\n|\r/).filter(line=>/^[^#]/.test(line)).filter(line=>/=/i.test(line)),parsedEnv=parseEnv(envArr);if(Object.keys(parsedEnv).length===0){output_manager_default.debug("Failed to parse env file.");return}return parsedEnv}function findChanges(oldEnv,newEnv){let added=[],changed=[];for(let key of Object.keys(newEnv))oldEnv[key]===void 0?added.push(key):oldEnv[key]!==newEnv[key]&&changed.push(key),delete oldEnv[key];let removed=Object.keys(oldEnv);return{added,changed,removed}}function buildDeltaString(oldEnv,newEnv){let{added,changed,removed}=findChanges(oldEnv,newEnv),deltaString="";return deltaString+=import_chalk.default.green(addDeltaSection("+",changed,!0)),deltaString+=import_chalk.default.green(addDeltaSection("+",added)),deltaString+=import_chalk.default.red(addDeltaSection("-",removed)),deltaString&&import_chalk.default.gray(` Changes:
|
|
8
|
+
`)+deltaString+`
|
|
9
|
+
`}function addDeltaSection(prefix,arr,changed=!1){return arr.length===0?"":arr.sort().map(item=>` ${prefix} ${item}${changed?" (Updated)":""}`).join(`
|
|
10
|
+
`)+`
|
|
11
|
+
`}var VERCEL_OIDC_TOKEN="VERCEL_OIDC_TOKEN",SENSITIVE_ENV_VALUE_PLACEHOLDER="[SENSITIVE]";var import_frameworks=__toESM(require_frameworks(),1);import{readFile as readFile2}from"node:fs/promises";import{join}from"node:path";var SERVER_ONLY_KEY_PATTERNS=["access_token","refresh_token","client_secret","webhook_secret","api_key","private_key","service_account","service_role","database_url","database_uri","db_url","postgres_url","postgres_uri","mysql_url","mongo_url","mongo_uri","redis_url","redis_uri","amqp_url","kafka_url","elasticsearch_url","password","passwd","pwd","secret","private","key","apikey","auth","token","jwt","signature","cert","pem","salt","bearer","credential","credentials","creds"],SAFE_KEY_HINT_TOKENS=["public","publishable","anon"],WELL_KNOWN_SECRET_NAMES=new Set(["DATABASE_URL","DATABASE_URL_UNPOOLED","POSTGRES_URL","POSTGRES_URL_NON_POOLING","POSTGRES_URL_NO_SSL","POSTGRES_URL_UNPOOLED","POSTGRES_PRISMA_URL","MONGODB_URI","MONGODB_URL","MONGO_URI","MONGO_URL","MYSQL_URL","MYSQL_URI","REDIS_URL","REDIS_TLS_URL","KV_URL","KV_REST_API_URL","UPSTASH_REDIS_REST_URL","GOOGLE_APPLICATION_CREDENTIALS","AWS_ACCESS_KEY_ID"]),SECRET_SEGMENT_PATTERN=/(?:^|[_-])(SECRET|PASSWORD|PASSWD|PASSPHRASE|PWD|PGPASSWORD|TOKEN|CREDENTIAL|JWT|DSN|APIKEY|PRIVATEKEY|SALT|PEPPER|MNEMONIC|PEM|CIPHER)S?(?:[_-]|$)/i,EXPLICIT_SECRET_TOKEN_PATTERN=/(?:^|[_-])(SECRET|PASSWORD|PASSWD|PASSPHRASE|PWD|PGPASSWORD|TOKEN|CREDENTIAL|MNEMONIC|PRIVATEKEY|APIKEY)S?(?:[_-]|$)/i,SECRET_COMPOUND_PATTERNS=[/(?:^|[_-])(?:API|PRIVATE|SIGNING|ENCRYPTION|SESSION|COOKIE|CSRF|HMAC|ACCESS|APP|WRITE)[_-]?(?:KEY|SECRET)S?(?:[_-]|$)/i,/(?:^|[_-])(?:ACCESS|REFRESH|BEARER|AUTH)[_-]?TOKENS?(?:[_-]|$)/i,/(?:^|[_-])(?:WEBHOOK|SIGNING)[_-]?SECRETS?(?:[_-]|$)/i,/(?:^|[_-])SERVICE[_-]?(?:ROLE(?:[_-]?KEYS?)?|ACCOUNTS?)(?:[_-]|$)/i],NON_CREDENTIAL_KEY_TOKENS=new Set(["PUBLIC","PUBLISHABLE","ANON","PRIMARY","PARTITION","FOREIGN","SORT","HASH","COMPOSITE","INDEX","UNIQUE","NATURAL","SURROGATE","CACHE","IDEMPOTENCY","LOOKUP","ROW","SHARD","CLUSTER","LICENSE","LICENCE","PRODUCT","TRANSLATION","TRANSLATIONS","I18N","LOCALE","RBAC","ACL","ROLE","ROLES","PERMISSION","PERMISSIONS","SCOPE","SCOPES","POLICY","POLICIES"]),GENERIC_KEY_SUFFIX_PATTERN=/(?:^|[_-])([A-Z0-9]+)[_-]KEYS?$/i,GENERIC_KEY_PREFIX_PATTERN=/^KEYS?[_-]([A-Z0-9]+)(?:[_-]|$)/i,DB_URL_PATTERN=/(?:^|_)(?:DATABASE|POSTGRES|MONGO|MONGODB|MYSQL|REDIS|NEON|PLANETSCALE|TURSO|RDS)(?:_[A-Z0-9_]*)?_(?:URL|URI)(?:_[A-Z0-9_]+)?$/i,SECRET_VALUE_PATTERNS=[/gh[opsru]_[A-Za-z0-9_]{20,}/,/github_pat_[A-Za-z0-9_]{20,}/,/glpat-[A-Za-z0-9_-]{20,}/,/(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{20,}/,/whsec_[A-Za-z0-9]{20,}/,/xox[abprs]-[A-Za-z0-9-]{20,}/,/xapp-[A-Za-z0-9-]{20,}/,/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/,/\bAIza[A-Za-z0-9_-]{30,}/,/sk-ant-[A-Za-z0-9_-]{20,}/,/sk-(?:proj|svcacct|admin)-[A-Za-z0-9_-]{20,}/,/\bsk-[A-Za-z0-9]{32,}\b/,/shp(?:at|ss|ca)_[a-fA-F0-9]{32}/,/npm_[A-Za-z0-9]{30,}/,/\bhf_[A-Za-z0-9_]{30,}/,/nvapi-[A-Za-z0-9_-]{40,}/,/SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}/,/key-[a-f0-9]{32}/,/glsa_[A-Za-z0-9_]{32}_[a-f0-9]{8}/,/pscale_pw_[A-Za-z0-9_-]{20,}/,/\bre_[A-Za-z0-9_]{30,}/,/dop_v1_[a-f0-9]{64}/,/sntrys_[A-Za-z0-9_-]{30,}/,/FlyV1 [A-Za-z0-9_-]{20,}/,/AccountKey=[A-Za-z0-9+/]{40,}=*/,/-----BEGIN [A-Z0-9 ]*PRIVATE KEY[A-Z0-9 ]*-----/,/-----BEGIN PGP MESSAGE-----/,/\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{8,}\b/,/[a-zA-Z][a-zA-Z0-9+.-]*:\/\/[A-Za-z0-9_.%-]*:[^@\s/]+(?<!\.\.)@/,/\bBearer\s+[A-Za-z0-9_+=/.-]{20,}/i,/(?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?token|refresh[_-]?token|private[_-]?key|auth)\s*[=:]\s*["']?[A-Za-z0-9_+=/.-]{12,}/i];function tokenize(key){return new Set(key.split(/(?<=[a-z])(?=[A-Z])/).flatMap(part=>part.split(/[_\-.]+/)).map(token=>token.toLowerCase()).filter(Boolean))}function hasSafeKeyHint(key){let tokens=tokenize(key);return SAFE_KEY_HINT_TOKENS.some(token=>tokens.has(token))}function hasGenericKeySuffix(key){let precedingToken=GENERIC_KEY_SUFFIX_PATTERN.exec(key)?.[1]?.toUpperCase();return!!(precedingToken&&!NON_CREDENTIAL_KEY_TOKENS.has(precedingToken))}function hasGenericKeyPrefix(key){let followingToken=GENERIC_KEY_PREFIX_PATTERN.exec(key)?.[1]?.toUpperCase();return!!(followingToken&&!NON_CREDENTIAL_KEY_TOKENS.has(followingToken))}function getMatchingServerOnlyKey(key){let normalized=key.replace(/(?<=[a-z])(?=[A-Z])/g,"_").toLowerCase().replace(/[-.]+/g,"_");for(let pattern of SERVER_ONLY_KEY_PATTERNS)if(pattern.includes("_")&&normalized.includes(pattern))return pattern;let tokens=tokenize(key);return SERVER_ONLY_KEY_PATTERNS.find(pattern=>!pattern.includes("_")&&tokens.has(pattern))??null}function looksLikeSecret(key){return!key||hasSafeKeyHint(key)?!1:WELL_KNOWN_SECRET_NAMES.has(key.toUpperCase())||SECRET_SEGMENT_PATTERN.test(key)||SECRET_COMPOUND_PATTERNS.some(pattern=>pattern.test(key))||DB_URL_PATTERN.test(key)?!0:hasGenericKeySuffix(key)||hasGenericKeyPrefix(key)}function looksLikeSecretValue(value){let trimmed=value.trim();return!!(trimmed&&SECRET_VALUE_PATTERNS.some(pattern=>pattern.test(trimmed)))}function shouldConfirmRotationBeforeDelete(env){return env.type==="system"?!1:EXPLICIT_SECRET_TOKEN_PATTERN.test(env.key)?!0:env.hasPublicPrefix||hasSafeKeyHint(env.key)?!1:looksLikeSecret(env.key)}function isFlagsSecretNeedingSplit(env){return env.key!=="FLAGS_SECRET"||env.type!=="plain"&&env.type!=="encrypted"?!1:env.targets.length+(env.customEnvironmentIds?.length??0)>1}function getEnvValueWarnings(value){let warnings=[],normalized=value.replace(/\n$/,"");return/^[ \t]+/.test(normalized)&&warnings.push({message:"starts with whitespace",requiresConfirmation:!1}),/[ \t]+$/.test(normalized)&&warnings.push({message:"ends with whitespace",requiresConfirmation:!1}),(normalized.includes("\r")||normalized.includes(`
|
|
12
|
+
`))&&warnings.push({message:"contains newlines",requiresConfirmation:!1}),value.includes("\0")&&warnings.push({message:"contains null characters",requiresConfirmation:!1}),value===""&&warnings.push({message:"is empty",requiresConfirmation:!0}),value.length>2&&(value.startsWith('"')&&value.endsWith('"')||value.startsWith("'")&&value.endsWith("'"))&&warnings.push({message:"includes surrounding quotes (these will be stored literally)",requiresConfirmation:!1}),warnings}function formatWarnings(warnings){if(warnings.length===0)return null;let messages=warnings.map(w=>w.message),startsIdx=messages.indexOf("starts with whitespace"),endsIdx=messages.indexOf("ends with whitespace");if(startsIdx!==-1&&endsIdx!==-1&&(messages.splice(Math.max(startsIdx,endsIdx),1),messages[Math.min(startsIdx,endsIdx)]="starts and ends with whitespace"),messages.length===1)return`Value ${messages[0]}`;if(messages.length===2)return`Value ${messages[0]} and ${messages[1]}`;let last=messages.pop();return`Value ${messages.join(", ")}, and ${last}`}var API_PUBLIC_PREFIXES=["NEXT_PUBLIC_","VUE_APP_","REACT_APP_","GATSBY_","GRIDSOME_","NUXT_PUBLIC_","STORYBOOK_","VITE_","PUBLIC_","EXPO_PUBLIC_","NG_APP_","REDWOOD_ENV_"],PUBLIC_PREFIXES=[...new Set([...API_PUBLIC_PREFIXES,...import_frameworks.frameworkList.map(f=>f.envPrefix).filter(prefix=>!!prefix)])];function hasOnlyWhitespaceWarnings(warnings){return warnings.length>0&&warnings.every(w=>w.message==="starts with whitespace"||w.message==="ends with whitespace")}function trimValue(value){return value.replace(/\n$/,"").trim()}function normalizeStdinEnvValue(value){let valueWithoutTrailingNewline=value;if(value.endsWith(`\r
|
|
13
|
+
`))valueWithoutTrailingNewline=value.slice(0,-2);else if(value.endsWith(`
|
|
14
|
+
`))valueWithoutTrailingNewline=value.slice(0,-1);else return{value,strippedTrailingNewline:!1};return valueWithoutTrailingNewline.includes(`
|
|
15
|
+
`)||valueWithoutTrailingNewline.includes("\r")?{value,strippedTrailingNewline:!1}:{value:valueWithoutTrailingNewline,strippedTrailingNewline:!0}}function getPublicPrefix(key){let upperKey=key.toUpperCase();return PUBLIC_PREFIXES.find(p=>upperKey.startsWith(p))||null}function getFrameworkPublicPrefix(frameworkSlug,key){let prefix=import_frameworks.frameworkList.find(framework=>framework.slug===frameworkSlug)?.envPrefix;return prefix&&key.toUpperCase().startsWith(prefix.toUpperCase())?prefix:null}function getApiPublicPrefix(key){let upperKey=key.toUpperCase();return API_PUBLIC_PREFIXES.find(prefix=>upperKey.startsWith(prefix))??null}function parseSvelteKitPublicEnvVarPrefix(config){if(!config.includes("publicPrefix"))return{status:"ready",prefix:null};let match=/publicPrefix:\s*(?:'(?<single>[^']*)'|"(?<double>[^"]*)"|`(?<template>[^`$]*)`)/.exec(config),prefix=match?.groups?.single??match?.groups?.double??match?.groups?.template;return prefix===void 0?{status:"unavailable"}:{status:"ready",prefix}}async function getLocalSvelteKitPublicPrefixes(cwd,rootDirectory){let projectRoot=rootDirectory?join(cwd,rootDirectory):cwd,config;try{config=await readFile2(join(projectRoot,"svelte.config.js"),"utf8")}catch{return}let parsed=parseSvelteKitPublicEnvVarPrefix(config);if(parsed.status!=="unavailable")return[parsed.prefix??"PUBLIC_","VITE_"]}function removePublicPrefix(key){let prefix=getPublicPrefix(key);return prefix?key.slice(prefix.length):key}async function validateEnvValue(opts){let finalValue=opts.initialValue,alreadyConfirmed=!1;if(opts.skipConfirm){let valueWarnings=getEnvValueWarnings(finalValue),warningMessage=formatWarnings(valueWarnings);warningMessage&&opts.showWarning(warningMessage)}else{let valueAccepted=!1;for(;!valueAccepted;){let valueWarnings=getEnvValueWarnings(finalValue),warningMessage=formatWarnings(valueWarnings);if(!warningMessage){valueAccepted=!0;break}opts.showWarning(warningMessage);let choices=hasOnlyWhitespaceWarnings(valueWarnings)?[{name:"Leave as is",value:"c"},{name:"Re-enter",value:"r"},{name:"Trim whitespace",value:"t"}]:[{name:"Leave as is",value:"c"},{name:"Re-enter",value:"r"}],action=await opts.selectAction(choices);action==="c"?(valueAccepted=!0,valueWarnings.some(w=>w.requiresConfirmation)&&(alreadyConfirmed=!0)):action==="t"?(finalValue=trimValue(finalValue),opts.showLog("Trimmed whitespace")):finalValue=await opts.promptForValue()}}return{finalValue,alreadyConfirmed}}function getEnvKeyWarnings(key){let warnings=[],matchingPrefix=getPublicPrefix(key);if(matchingPrefix){let nameWithoutPrefix=key.slice(matchingPrefix.length);looksLikeSecret(nameWithoutPrefix)&&getMatchingServerOnlyKey(nameWithoutPrefix)?warnings.push({message:`\`${matchingPrefix}\` exposes \`${key}\` to anyone visiting your site`,requiresConfirmation:!0}):warnings.push({message:`\`${matchingPrefix}\` exposes this value to anyone visiting your site`,requiresConfirmation:!1})}return warnings}var ENV_VISIBILITY_DEPRECATION_MESSAGE="`--visibility` is deprecated. Use `--type` instead.";function invalidTypeOptionError(optionName,value){if(!(value==="config"||value==="secret"))return value==="sensitive"?`The \`${optionName}\` flag accepts \`config\` or \`secret\`. Use \`--type secret\` or the legacy \`--sensitive\` flag.`:value==="plain"||value==="encrypted"?`The \`${optionName}\` flag accepts \`config\` or \`secret\`. Use \`--type config\` for readable values.`:`The \`${optionName}\` flag must be either \`config\` or \`secret\`.`}function resolveEnvVarTypeOption(options){let usedDeprecatedVisibility=options.visibility!==void 0;if(options.type!==void 0){let error=invalidTypeOptionError("--type",options.type);if(error)return{usedDeprecatedVisibility,error,errorReason:"invalid_type"}}if(options.visibility!==void 0){let error=invalidTypeOptionError("--visibility",options.visibility);if(error)return{usedDeprecatedVisibility,error,errorReason:"invalid_visibility"}}return options.type!==void 0&&options.visibility!==void 0&&options.type!==options.visibility?{usedDeprecatedVisibility,error:`\`--type ${options.type}\` conflicts with \`--visibility ${options.visibility}\`. \`--visibility\` is a deprecated alias of \`--type\`; remove it.`,errorReason:"conflicting_type_visibility"}:options.type!==void 0?{explicitVisibility:options.type,source:"type",usedDeprecatedVisibility}:options.visibility!==void 0?{explicitVisibility:options.visibility,source:"visibility",usedDeprecatedVisibility}:{usedDeprecatedVisibility}}function isSecretEnvVar(env){return env.type==="sensitive"||env.visibility==="secret"}function formatVisibilityLabel(visibility,type){let resolved=visibility??visibilityFromEnvType(type);if(resolved==="config")return"Config";if(resolved==="secret")return"Secret"}function visibilityFromEnvType(type){if(type==="sensitive")return"secret";if(type==="plain"||type==="encrypted")return"config"}function hasNonDevelopmentTarget(envTargets){return envTargets.some(target=>target!=="development")}function getPublicPrefixSecretVisibilityError(key,options){let publicPrefix=getApiPublicPrefix(key);if(!publicPrefix||!(options.visibility==="secret"||options.type==="sensitive"))return null;let privateKey=key.slice(publicPrefix.length);return options.context==="update"?`\`${publicPrefix}\` exposes this value to anyone visiting your site, so \`${key}\` cannot be a Secret. To keep it private, add \`${privateKey}\` as a Secret, then remove \`${key}\`. If the value is safe to expose, keep it as Config.`:`\`${publicPrefix}\` exposes this value to anyone visiting your site, so \`${key}\` cannot be a Secret. To keep it private, rename the variable to \`${privateKey}\` and keep the Secret type. If the value is safe to expose, use \`--type config\`.`}function shouldOmitInferredVisibility(key,envTargets,teamSensitivePolicyOn){return!getApiPublicPrefix(key)||!hasNonDevelopmentTarget(envTargets)?!1:teamSensitivePolicyOn}function resolveEnvVarVisibility(options){if(options.explicitVisibility!==void 0){if(options.explicitVisibility!=="config"&&options.explicitVisibility!=="secret"){let optionName=options.explicitOptionSource==="visibility"?"--visibility":"--type";return{error:options.explicitVisibility==="sensitive"?`The \`${optionName}\` flag accepts \`config\` or \`secret\`. Use \`--type secret\` or the legacy \`--sensitive\` flag.`:options.explicitVisibility==="plain"||options.explicitVisibility==="encrypted"?`The \`${optionName}\` flag accepts \`config\` or \`secret\`. Use \`--type config\` for readable values.`:`The \`${optionName}\` flag must be either \`config\` or \`secret\`.`}}let publicPrefixError2=getPublicPrefixSecretVisibilityError(options.key,{visibility:options.explicitVisibility,type:options.type,context:options.context});return publicPrefixError2?{error:publicPrefixError2}:{visibility:options.explicitVisibility}}let inferred=visibilityFromEnvType(options.type);if(inferred===void 0)return{};if(shouldOmitInferredVisibility(options.key,options.envTargets,options.teamSensitivePolicyOn))return{};let publicPrefixError=getPublicPrefixSecretVisibilityError(options.key,{visibility:inferred,type:options.type,context:options.context});return publicPrefixError?{error:publicPrefixError}:{visibility:inferred}}function getUnavailableSecretValuesMessage(environment,count){let values=count===1?"value":"values";return environment==="development"?`${count} Development Secret ${values} ${count===1?"was":"were"} not returned by Vercel.`:`${count} Secret ${values} cannot be pulled from the \`${environment}\` Environment.`}function getLocalSecretFallbackMessage(count){return` Define ${count===1?"it":"them"} in a local .env file.`}var CONTENTS_HEADER="# Created by Vercel CLI";function updateOidcTokenContents(existing,token){let assignment=`${VERCEL_OIDC_TOKEN}="${escapeValue(token)}"`,oidcAssignment=new RegExp(`^(\\uFEFF?)[\\t ]*(?:export[\\t ]+)?${VERCEL_OIDC_TOKEN}[\\t ]*=[^\\r\\n]*(\\r\\n|\\n|\\r|$)`,"gm"),tokenWritten=!1,withoutDuplicates=existing.replace(oidcAssignment,(_match,byteOrderMark,lineEnding2)=>token!==void 0&&!tokenWritten?(tokenWritten=!0,`${byteOrderMark}${assignment}${lineEnding2}`):byteOrderMark);if(token===void 0||tokenWritten)return withoutDuplicates;let lineEnding=withoutDuplicates.match(/\r\n|\n|\r/)?.[0]??`
|
|
16
|
+
`,hasTrailingLineEnding=/(?:\r\n|\n|\r)$/.test(withoutDuplicates),hasTrailingBlankLine=/(?:\r\n|\n|\r){2}$/.test(withoutDuplicates),separator=withoutDuplicates.length===0||hasTrailingBlankLine?"":hasTrailingLineEnding?lineEnding:`${lineEnding}${lineEnding}`;return`${withoutDuplicates}${separator}${CONTENTS_HEADER}${lineEnding}${assignment}${lineEnding}`}function escapeValue(value){return value?value.replace(/\n/g,"\\n").replace(/\r/g,"\\r"):""}var import_error_utils=__toESM(require_dist(),1);var import_json_parse_better_errors=__toESM(require_json_parse_better_errors(),1);var EnvPullTelemetryClient=class extends TelemetryClient{trackCliArgumentFilename(filename){filename&&this.trackCliArgument({arg:"filename",value:this.redactedValue})}trackCliOptionEnvironment(environment){environment&&this.trackCliOption({option:"environment",value:STANDARD_ENVIRONMENTS.includes(environment)?environment:this.redactedValue})}trackCliOptionGitBranch(gitBranch){gitBranch&&this.trackCliOption({option:"git-branch",value:this.redactedValue})}trackCliFlagYes(yes){yes&&this.trackCliFlag("yes")}trackCliOptionDeployment(deployment){deployment&&this.trackCliOption({option:"deployment",value:this.redactedValue})}trackCliOptionId(id){id&&this.trackCliOption({option:"id",value:this.redactedValue})}};var CONTENTS_PREFIX=`# Created by Vercel CLI
|
|
17
|
+
`;function printEnvPullWarning(message){output_manager_default.print(`${import_chalk2.default.yellow("!")} ${message}
|
|
18
|
+
`)}function readHeadSync(path,length){let buffer=Buffer.alloc(length),fd=openSync(path,"r");try{readSync(fd,buffer,0,buffer.length,null)}finally{closeSync(fd)}return buffer.toString()}function tryReadHeadSync(path,length){try{return readHeadSync(path,length)}catch(err){if(!(0,import_error_utils.isErrnoException)(err)||err.code!=="ENOENT")throw err}}var VARIABLES_TO_IGNORE=["VERCEL_ANALYTICS_ID","VERCEL_SPEED_INSIGHTS_ID","VERCEL_WEB_ANALYTICS_ID"],SENSITIVE_PLACEHOLDER=SENSITIVE_ENV_VALUE_PLACEHOLDER;async function getRedactedSensitiveKeys(client,projectId,source,target,gitBranch,records){let emptyKeys=Object.keys(records).filter(key=>!records[key]);if(!projectId||emptyKeys.length===0)return new Set;try{let{envs}=await getEnvRecords(client,projectId,source,{target,gitBranch}),sensitiveKeys=new Set(envs.filter(isSecretEnvVar).map(env=>env.key));return new Set(emptyKeys.filter(key=>sensitiveKeys.has(key)))}catch{return new Set}}async function pull(client,argv,source="vercel-cli:env:pull",options={}){let telemetryClient=new EnvPullTelemetryClient({opts:{store:client.telemetryEventStore}}),parsedArgs,flagsSpecification=getFlagsSpecification(pullSubcommand.options);try{parsedArgs=parseArguments(argv,flagsSpecification)}catch(err){return printError(err),2}let{args,flags:opts}=parsedArgs;if(args.length>1)return output_manager_default.error(`Invalid number of arguments. Usage: ${getCommandName("env pull <file>")}`),2;let[rawFilename]=args,filename=rawFilename||".env.local",skipConfirmation=opts["--yes"],gitBranch=opts["--git-branch"];telemetryClient.trackCliArgumentFilename(args[0]),telemetryClient.trackCliFlagYes(skipConfirmation),telemetryClient.trackCliOptionGitBranch(gitBranch),telemetryClient.trackCliOptionEnvironment(opts["--environment"]),telemetryClient.trackCliOptionDeployment(opts["--deployment"]),telemetryClient.trackCliOptionId(opts["--id"]),telemetryClient.trackCliOptionProject(opts["--project"]);let deploymentFlag=getRenamedOption(opts,"--deployment","--id");if("error"in deploymentFlag)return reportRenamedOptionError(client,deploymentFlag.error);let link=await resolveProjectContext({client,projectNameOrId:opts["--project"],skipOwnerLookup:!0});if(link.status==="error")return link.exitCode;if(link.status==="not_linked"){if(client.nonInteractive){let argv2=renameOptionInArgs(client.argv,"--id","--deployment"),preserved=getPreservedArgsForEnvPull(argv2),linkArgv=[...argv2.slice(0,2),"link","--scope","<scope>",...preserved];outputAgentError(client,{status:"error",reason:"not_linked",message:`Your codebase isn't linked to a project on Vercel. Run \`${getCommandNamePlain("link")}\` to begin. Use \`--yes\` for non-interactive; use \`--scope\` or \`--project\` to specify team or project.`,next:[{command:buildCommandWithYes(linkArgv)},{command:buildCommandWithYes(argv2)}]},1)}if(!client.nonInteractive&&client.stdin.isTTY&&!skipConfirmation){let ensuredLink=await ensureLink("env pull",client,client.cwd,{link,pullEnv:!1});if(typeof ensuredLink=="number")return ensuredLink;link=ensuredLink}else return output_manager_default.error(`Your codebase isn\u2019t linked to a project on Vercel. Run ${getCommandName("link")} to begin.`),1}client.config.currentTeam=link.org.type==="team"?link.org.id:void 0;let deploymentId=deploymentFlag.value;if(deploymentId&&opts["--project"]){let deployment=await getDeployment(client,link.org.slug||link.org.id,deploymentId);if(deployment.projectId&&deployment.projectId!==link.project.id)return output_manager_default.error(`Deployment ${import_chalk2.default.bold(deploymentId)} does not belong to project ${import_chalk2.default.bold(link.project.name)}.`),1}let environment=parseTarget({flagName:"environment",flags:opts})||"development";return await envPullCommandLogic(client,filename,!!skipConfirmation,environment,link,gitBranch,client.cwd,source,deploymentId,options),0}async function envPullCommandLogic(client,filename,skipConfirmation,environment,link,gitBranch,cwd,source,deploymentId,{oidcTokenOnly=!1}={}){let fullPath=resolve(cwd,filename),head=tryReadHeadSync(fullPath,Buffer.byteLength(CONTENTS_PREFIX)),exists=typeof head<"u";if(head===CONTENTS_PREFIX&&!oidcTokenOnly)output_manager_default.log(`Overwriting existing ${import_chalk2.default.bold(filename)} file`);else if(exists&&!skipConfirmation&&!oidcTokenOnly){if(client.nonInteractive){let preserved=getPreservedArgsForEnvPull(renameOptionInArgs(client.argv,"--id","--deployment")).filter(arg=>arg!=="--yes"&&arg!=="-y"),suffix=preserved.length>0?` ${preserved.join(" ")}`:"";outputActionRequired(client,{status:"action_required",reason:"env_file_exists",message:`File ${param(filename)} already exists and was not created by Vercel CLI. Use --yes to overwrite or specify a different filename.`,next:[{command:getCommandNamePlain(`env pull ${filename} --yes${suffix}`),when:"Overwrite this file"},{command:getCommandNamePlain(`env pull <filename>${suffix}`),when:"Use a different filename"}]})}if(!await client.input.confirm(`Found existing file ${param(filename)}. Do you want to overwrite?`,!1)){output_manager_default.log("Canceled");return}}let projectSlugLink=link.org.slug?formatProject(link.org.slug,link.project.name):import_chalk2.default.bold(link.project.name),downloadMessage=oidcTokenOnly?`Downloading a fresh \`${import_chalk2.default.cyan(VERCEL_OIDC_TOKEN)}\` for ${projectSlugLink}`:gitBranch?`Downloading \`${import_chalk2.default.cyan(environment)}\` environment variables for ${projectSlugLink} and any overrides for branch ${import_chalk2.default.cyan(gitBranch)}`:`Downloading \`${import_chalk2.default.cyan(environment)}\` environment variables for ${projectSlugLink}`;output_manager_default.log(downloadMessage),output_manager_default.spinner("Downloading");let pullId=deploymentId||link.project.id,pullResult=await pullEnvRecords(client,pullId,source,{target:environment||"development",gitBranch}),records=deploymentId?pullResult.buildEnv:pullResult.env,deltaString="",oldEnv;exists&&!oidcTokenOnly&&(oldEnv=await createEnvObject(fullPath));let contents,fileChanged=!0,keptLocalKeys=[],preservedLocalSecretKeys=[],redactedSecretCount=0,placeholderSecretCount=0;if(oidcTokenOnly){let existingContents=exists?await(0,import_fs_extra2.readFile)(fullPath,"utf8"):"";contents=updateOidcTokenContents(existingContents,records[VERCEL_OIDC_TOKEN]||void 0),fileChanged=contents!==existingContents}else{let sensitiveKeys=await getRedactedSensitiveKeys(client,deploymentId?void 0:link.project.id,source,environment,gitBranch,records);redactedSecretCount=sensitiveKeys.size;let mergedRecords={...records};for(let key of sensitiveKeys){let localValue=oldEnv?.[key];localValue&&localValue!==SENSITIVE_PLACEHOLDER?(mergedRecords[key]=localValue,preservedLocalSecretKeys.push(key)):(mergedRecords[key]=SENSITIVE_PLACEHOLDER,placeholderSecretCount++)}if(oldEnv)for(let[key,value]of Object.entries(oldEnv))!(key in mergedRecords)&&key!==VERCEL_OIDC_TOKEN&&!VARIABLES_TO_IGNORE.includes(key)&&(mergedRecords[key]=value,keptLocalKeys.push(key));if(contents=CONTENTS_PREFIX+Object.keys(mergedRecords).sort().filter(key=>!VARIABLES_TO_IGNORE.includes(key)).map(key=>`${key}="${escapeValue2(mergedRecords[key])}"`).join(`
|
|
19
|
+
`)+`
|
|
20
|
+
`,oldEnv){let newEnv=(0,import_json_parse_better_errors.default)(JSON.stringify(mergedRecords).replace(/\\"/g,""));deltaString=buildDeltaString(oldEnv,newEnv)}}if(fileChanged&&await(0,import_fs_extra2.outputFile)(fullPath,contents,"utf8"),deltaString?output_manager_default.print(`
|
|
21
|
+
`+deltaString):oldEnv&&exists&&output_manager_default.log("No changes found."),keptLocalKeys.length>0&&output_manager_default.log(`Kept ${keptLocalKeys.sort().map(key=>import_chalk2.default.bold(key)).join(", ")} (defined locally, not found in the ${import_chalk2.default.cyan(environment)} Environment)`),redactedSecretCount>0){let preservedMessage=preservedLocalSecretKeys.length>0?` Kept ${preservedLocalSecretKeys.length} existing local ${preservedLocalSecretKeys.length===1?"value":"values"}.`:"",placeholderMessage=placeholderSecretCount>0?` Wrote "${SENSITIVE_PLACEHOLDER}" ${placeholderSecretCount===1?"as a placeholder":"as placeholders"} for the remaining ${placeholderSecretCount===1?"value":"values"}; replace ${placeholderSecretCount===1?"it":"them"} with local-only values.`:"";printEnvPullWarning(`${getUnavailableSecretValuesMessage(environment,redactedSecretCount)}${preservedMessage}${placeholderMessage}`)}let isGitIgnoreUpdated=!1,fileExistsAfterPull=exists||contents.length>0;if(filename===".env.local"&&fileExistsAfterPull){let rootPath=link.repoRoot??cwd;isGitIgnoreUpdated=await addToGitIgnore(rootPath,".env*")}if(!fileChanged&&!isGitIgnoreUpdated){output_manager_default.stopSpinner();return}if(output_manager_default.print(`
|
|
22
|
+
`),!fileChanged){printAlignedLabel("Updated",`.gitignore for ${filename}`,{gutter:"\u2713"});return}printAlignedLabel(exists?"Updated":"Created",`${filename} file${isGitIgnoreUpdated?" and added it to .gitignore":""}`,{gutter:"\u2713"})}function escapeValue2(value){return value?value.replace(new RegExp(`
|
|
23
|
+
`,"g"),"\\n").replace(new RegExp("\r","g"),"\\r"):""}export{createEnvObject,VERCEL_OIDC_TOKEN,SENSITIVE_ENV_VALUE_PLACEHOLDER,looksLikeSecret,looksLikeSecretValue,shouldConfirmRotationBeforeDelete,isFlagsSecretNeedingSplit,normalizeStdinEnvValue,getPublicPrefix,getFrameworkPublicPrefix,getApiPublicPrefix,getLocalSvelteKitPublicPrefixes,removePublicPrefix,validateEnvValue,getEnvKeyWarnings,ENV_VISIBILITY_DEPRECATION_MESSAGE,resolveEnvVarTypeOption,isSecretEnvVar,formatVisibilityLabel,getPublicPrefixSecretVisibilityError,resolveEnvVarVisibility,getUnavailableSecretValuesMessage,getLocalSecretFallbackMessage,SENSITIVE_PLACEHOLDER,pull,envPullCommandLogic};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
function isValidName(name=""){let blacklist=":/#?&@%+~".split("");return!name.split("").every(c=>blacklist.includes(c))}export{isValidName};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{__commonJS}from"./chunk-BZENIQ7N.js";var require_is_date=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/is_date/index.js"(exports,module){function isDate(argument){return argument instanceof Date}module.exports=isDate}});var require_parse=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/parse/index.js"(exports,module){var isDate=require_is_date(),MILLISECONDS_IN_HOUR=36e5,MILLISECONDS_IN_MINUTE=6e4,DEFAULT_ADDITIONAL_DIGITS=2,parseTokenDateTimeDelimeter=/[T ]/,parseTokenPlainTime=/:/,parseTokenYY=/^(\d{2})$/,parseTokensYYY=[/^([+-]\d{2})$/,/^([+-]\d{3})$/,/^([+-]\d{4})$/],parseTokenYYYY=/^(\d{4})/,parseTokensYYYYY=[/^([+-]\d{4})/,/^([+-]\d{5})/,/^([+-]\d{6})/],parseTokenMM=/^-(\d{2})$/,parseTokenDDD=/^-?(\d{3})$/,parseTokenMMDD=/^-?(\d{2})-?(\d{2})$/,parseTokenWww=/^-?W(\d{2})$/,parseTokenWwwD=/^-?W(\d{2})-?(\d{1})$/,parseTokenHH=/^(\d{2}([.,]\d*)?)$/,parseTokenHHMM=/^(\d{2}):?(\d{2}([.,]\d*)?)$/,parseTokenHHMMSS=/^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/,parseTokenTimezone=/([Z+-].*)$/,parseTokenTimezoneZ=/^(Z)$/,parseTokenTimezoneHH=/^([+-])(\d{2})$/,parseTokenTimezoneHHMM=/^([+-])(\d{2}):?(\d{2})$/;function parse(argument,dirtyOptions){if(isDate(argument))return new Date(argument.getTime());if(typeof argument!="string")return new Date(argument);var options=dirtyOptions||{},additionalDigits=options.additionalDigits;additionalDigits==null?additionalDigits=DEFAULT_ADDITIONAL_DIGITS:additionalDigits=Number(additionalDigits);var dateStrings=splitDateString(argument),parseYearResult=parseYear(dateStrings.date,additionalDigits),year=parseYearResult.year,restDateString=parseYearResult.restDateString,date=parseDate(restDateString,year);if(date){var timestamp=date.getTime(),time=0,offset;return dateStrings.time&&(time=parseTime(dateStrings.time)),dateStrings.timezone?offset=parseTimezone(dateStrings.timezone):(offset=new Date(timestamp+time).getTimezoneOffset(),offset=new Date(timestamp+time+offset*MILLISECONDS_IN_MINUTE).getTimezoneOffset()),new Date(timestamp+time+offset*MILLISECONDS_IN_MINUTE)}else return new Date(argument)}function splitDateString(dateString){var dateStrings={},array=dateString.split(parseTokenDateTimeDelimeter),timeString;if(parseTokenPlainTime.test(array[0])?(dateStrings.date=null,timeString=array[0]):(dateStrings.date=array[0],timeString=array[1]),timeString){var token=parseTokenTimezone.exec(timeString);token?(dateStrings.time=timeString.replace(token[1],""),dateStrings.timezone=token[1]):dateStrings.time=timeString}return dateStrings}function parseYear(dateString,additionalDigits){var parseTokenYYY=parseTokensYYY[additionalDigits],parseTokenYYYYY=parseTokensYYYYY[additionalDigits],token;if(token=parseTokenYYYY.exec(dateString)||parseTokenYYYYY.exec(dateString),token){var yearString=token[1];return{year:parseInt(yearString,10),restDateString:dateString.slice(yearString.length)}}if(token=parseTokenYY.exec(dateString)||parseTokenYYY.exec(dateString),token){var centuryString=token[1];return{year:parseInt(centuryString,10)*100,restDateString:dateString.slice(centuryString.length)}}return{year:null}}function parseDate(dateString,year){if(year===null)return null;var token,date,month,week;if(dateString.length===0)return date=new Date(0),date.setUTCFullYear(year),date;if(token=parseTokenMM.exec(dateString),token)return date=new Date(0),month=parseInt(token[1],10)-1,date.setUTCFullYear(year,month),date;if(token=parseTokenDDD.exec(dateString),token){date=new Date(0);var dayOfYear=parseInt(token[1],10);return date.setUTCFullYear(year,0,dayOfYear),date}if(token=parseTokenMMDD.exec(dateString),token){date=new Date(0),month=parseInt(token[1],10)-1;var day=parseInt(token[2],10);return date.setUTCFullYear(year,month,day),date}if(token=parseTokenWww.exec(dateString),token)return week=parseInt(token[1],10)-1,dayOfISOYear(year,week);if(token=parseTokenWwwD.exec(dateString),token){week=parseInt(token[1],10)-1;var dayOfWeek=parseInt(token[2],10)-1;return dayOfISOYear(year,week,dayOfWeek)}return null}function parseTime(timeString){var token,hours,minutes;if(token=parseTokenHH.exec(timeString),token)return hours=parseFloat(token[1].replace(",",".")),hours%24*MILLISECONDS_IN_HOUR;if(token=parseTokenHHMM.exec(timeString),token)return hours=parseInt(token[1],10),minutes=parseFloat(token[2].replace(",",".")),hours%24*MILLISECONDS_IN_HOUR+minutes*MILLISECONDS_IN_MINUTE;if(token=parseTokenHHMMSS.exec(timeString),token){hours=parseInt(token[1],10),minutes=parseInt(token[2],10);var seconds=parseFloat(token[3].replace(",","."));return hours%24*MILLISECONDS_IN_HOUR+minutes*MILLISECONDS_IN_MINUTE+seconds*1e3}return null}function parseTimezone(timezoneString){var token,absoluteOffset;return token=parseTokenTimezoneZ.exec(timezoneString),token?0:(token=parseTokenTimezoneHH.exec(timezoneString),token?(absoluteOffset=parseInt(token[2],10)*60,token[1]==="+"?-absoluteOffset:absoluteOffset):(token=parseTokenTimezoneHHMM.exec(timezoneString),token?(absoluteOffset=parseInt(token[2],10)*60+parseInt(token[3],10),token[1]==="+"?-absoluteOffset:absoluteOffset):0))}function dayOfISOYear(isoYear,week,day){week=week||0,day=day||0;var date=new Date(0);date.setUTCFullYear(isoYear,0,4);var fourthOfJanuaryDay=date.getUTCDay()||7,diff=week*7+day+1-fourthOfJanuaryDay;return date.setUTCDate(date.getUTCDate()+diff),date}module.exports=parse}});var require_start_of_year=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/start_of_year/index.js"(exports,module){var parse=require_parse();function startOfYear(dirtyDate){var cleanDate=parse(dirtyDate),date=new Date(0);return date.setFullYear(cleanDate.getFullYear(),0,1),date.setHours(0,0,0,0),date}module.exports=startOfYear}});var require_start_of_day=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/start_of_day/index.js"(exports,module){var parse=require_parse();function startOfDay(dirtyDate){var date=parse(dirtyDate);return date.setHours(0,0,0,0),date}module.exports=startOfDay}});var require_difference_in_calendar_days=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/difference_in_calendar_days/index.js"(exports,module){var startOfDay=require_start_of_day(),MILLISECONDS_IN_MINUTE=6e4,MILLISECONDS_IN_DAY=864e5;function differenceInCalendarDays(dirtyDateLeft,dirtyDateRight){var startOfDayLeft=startOfDay(dirtyDateLeft),startOfDayRight=startOfDay(dirtyDateRight),timestampLeft=startOfDayLeft.getTime()-startOfDayLeft.getTimezoneOffset()*MILLISECONDS_IN_MINUTE,timestampRight=startOfDayRight.getTime()-startOfDayRight.getTimezoneOffset()*MILLISECONDS_IN_MINUTE;return Math.round((timestampLeft-timestampRight)/MILLISECONDS_IN_DAY)}module.exports=differenceInCalendarDays}});var require_get_day_of_year=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/get_day_of_year/index.js"(exports,module){var parse=require_parse(),startOfYear=require_start_of_year(),differenceInCalendarDays=require_difference_in_calendar_days();function getDayOfYear(dirtyDate){var date=parse(dirtyDate),diff=differenceInCalendarDays(date,startOfYear(date)),dayOfYear=diff+1;return dayOfYear}module.exports=getDayOfYear}});var require_start_of_week=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/start_of_week/index.js"(exports,module){var parse=require_parse();function startOfWeek(dirtyDate,dirtyOptions){var weekStartsOn=dirtyOptions&&Number(dirtyOptions.weekStartsOn)||0,date=parse(dirtyDate),day=date.getDay(),diff=(day<weekStartsOn?7:0)+day-weekStartsOn;return date.setDate(date.getDate()-diff),date.setHours(0,0,0,0),date}module.exports=startOfWeek}});var require_start_of_iso_week=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/start_of_iso_week/index.js"(exports,module){var startOfWeek=require_start_of_week();function startOfISOWeek(dirtyDate){return startOfWeek(dirtyDate,{weekStartsOn:1})}module.exports=startOfISOWeek}});var require_get_iso_year=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/get_iso_year/index.js"(exports,module){var parse=require_parse(),startOfISOWeek=require_start_of_iso_week();function getISOYear(dirtyDate){var date=parse(dirtyDate),year=date.getFullYear(),fourthOfJanuaryOfNextYear=new Date(0);fourthOfJanuaryOfNextYear.setFullYear(year+1,0,4),fourthOfJanuaryOfNextYear.setHours(0,0,0,0);var startOfNextYear=startOfISOWeek(fourthOfJanuaryOfNextYear),fourthOfJanuaryOfThisYear=new Date(0);fourthOfJanuaryOfThisYear.setFullYear(year,0,4),fourthOfJanuaryOfThisYear.setHours(0,0,0,0);var startOfThisYear=startOfISOWeek(fourthOfJanuaryOfThisYear);return date.getTime()>=startOfNextYear.getTime()?year+1:date.getTime()>=startOfThisYear.getTime()?year:year-1}module.exports=getISOYear}});var require_start_of_iso_year=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/start_of_iso_year/index.js"(exports,module){var getISOYear=require_get_iso_year(),startOfISOWeek=require_start_of_iso_week();function startOfISOYear(dirtyDate){var year=getISOYear(dirtyDate),fourthOfJanuary=new Date(0);fourthOfJanuary.setFullYear(year,0,4),fourthOfJanuary.setHours(0,0,0,0);var date=startOfISOWeek(fourthOfJanuary);return date}module.exports=startOfISOYear}});var require_get_iso_week=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/get_iso_week/index.js"(exports,module){var parse=require_parse(),startOfISOWeek=require_start_of_iso_week(),startOfISOYear=require_start_of_iso_year(),MILLISECONDS_IN_WEEK=6048e5;function getISOWeek(dirtyDate){var date=parse(dirtyDate),diff=startOfISOWeek(date).getTime()-startOfISOYear(date).getTime();return Math.round(diff/MILLISECONDS_IN_WEEK)+1}module.exports=getISOWeek}});var require_is_valid=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/is_valid/index.js"(exports,module){var isDate=require_is_date();function isValid(dirtyDate){if(isDate(dirtyDate))return!isNaN(dirtyDate);throw new TypeError(toString.call(dirtyDate)+" is not an instance of Date")}module.exports=isValid}});var require_build_distance_in_words_locale=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/locale/en/build_distance_in_words_locale/index.js"(exports,module){function buildDistanceInWordsLocale(){var distanceInWordsLocale={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}};function localize(token,count,options){options=options||{};var result;return typeof distanceInWordsLocale[token]=="string"?result=distanceInWordsLocale[token]:count===1?result=distanceInWordsLocale[token].one:result=distanceInWordsLocale[token].other.replace("{{count}}",count),options.addSuffix?options.comparison>0?"in "+result:result+" ago":result}return{localize}}module.exports=buildDistanceInWordsLocale}});var require_build_formatting_tokens_reg_exp=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/locale/_lib/build_formatting_tokens_reg_exp/index.js"(exports,module){var commonFormatterKeys=["M","MM","Q","D","DD","DDD","DDDD","d","E","W","WW","YY","YYYY","GG","GGGG","H","HH","h","hh","m","mm","s","ss","S","SS","SSS","Z","ZZ","X","x"];function buildFormattingTokensRegExp(formatters){var formatterKeys=[];for(var key in formatters)formatters.hasOwnProperty(key)&&formatterKeys.push(key);var formattingTokens=commonFormatterKeys.concat(formatterKeys).sort().reverse(),formattingTokensRegExp=new RegExp("(\\[[^\\[]*\\])|(\\\\)?("+formattingTokens.join("|")+"|.)","g");return formattingTokensRegExp}module.exports=buildFormattingTokensRegExp}});var require_build_format_locale=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/locale/en/build_format_locale/index.js"(exports,module){var buildFormattingTokensRegExp=require_build_formatting_tokens_reg_exp();function buildFormatLocale(){var months3char=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],monthsFull=["January","February","March","April","May","June","July","August","September","October","November","December"],weekdays2char=["Su","Mo","Tu","We","Th","Fr","Sa"],weekdays3char=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],weekdaysFull=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],meridiemUppercase=["AM","PM"],meridiemLowercase=["am","pm"],meridiemFull=["a.m.","p.m."],formatters={MMM:function(date){return months3char[date.getMonth()]},MMMM:function(date){return monthsFull[date.getMonth()]},dd:function(date){return weekdays2char[date.getDay()]},ddd:function(date){return weekdays3char[date.getDay()]},dddd:function(date){return weekdaysFull[date.getDay()]},A:function(date){return date.getHours()/12>=1?meridiemUppercase[1]:meridiemUppercase[0]},a:function(date){return date.getHours()/12>=1?meridiemLowercase[1]:meridiemLowercase[0]},aa:function(date){return date.getHours()/12>=1?meridiemFull[1]:meridiemFull[0]}},ordinalFormatters=["M","D","DDD","d","Q","W"];return ordinalFormatters.forEach(function(formatterToken){formatters[formatterToken+"o"]=function(date,formatters2){return ordinal(formatters2[formatterToken](date))}}),{formatters,formattingTokensRegExp:buildFormattingTokensRegExp(formatters)}}function ordinal(number){var rem100=number%100;if(rem100>20||rem100<10)switch(rem100%10){case 1:return number+"st";case 2:return number+"nd";case 3:return number+"rd"}return number+"th"}module.exports=buildFormatLocale}});var require_en=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/locale/en/index.js"(exports,module){var buildDistanceInWordsLocale=require_build_distance_in_words_locale(),buildFormatLocale=require_build_format_locale();module.exports={distanceInWords:buildDistanceInWordsLocale(),format:buildFormatLocale()}}});var require_format=__commonJS({"../../node_modules/.pnpm/date-fns@1.29.0/node_modules/date-fns/format/index.js"(exports,module){var getDayOfYear=require_get_day_of_year(),getISOWeek=require_get_iso_week(),getISOYear=require_get_iso_year(),parse=require_parse(),isValid=require_is_valid(),enLocale=require_en();function format(dirtyDate,dirtyFormatStr,dirtyOptions){var formatStr=dirtyFormatStr?String(dirtyFormatStr):"YYYY-MM-DDTHH:mm:ss.SSSZ",options=dirtyOptions||{},locale=options.locale,localeFormatters=enLocale.format.formatters,formattingTokensRegExp=enLocale.format.formattingTokensRegExp;locale&&locale.format&&locale.format.formatters&&(localeFormatters=locale.format.formatters,locale.format.formattingTokensRegExp&&(formattingTokensRegExp=locale.format.formattingTokensRegExp));var date=parse(dirtyDate);if(!isValid(date))return"Invalid Date";var formatFn=buildFormatFn(formatStr,localeFormatters,formattingTokensRegExp);return formatFn(date)}var formatters={M:function(date){return date.getMonth()+1},MM:function(date){return addLeadingZeros(date.getMonth()+1,2)},Q:function(date){return Math.ceil((date.getMonth()+1)/3)},D:function(date){return date.getDate()},DD:function(date){return addLeadingZeros(date.getDate(),2)},DDD:function(date){return getDayOfYear(date)},DDDD:function(date){return addLeadingZeros(getDayOfYear(date),3)},d:function(date){return date.getDay()},E:function(date){return date.getDay()||7},W:function(date){return getISOWeek(date)},WW:function(date){return addLeadingZeros(getISOWeek(date),2)},YY:function(date){return addLeadingZeros(date.getFullYear(),4).substr(2)},YYYY:function(date){return addLeadingZeros(date.getFullYear(),4)},GG:function(date){return String(getISOYear(date)).substr(2)},GGGG:function(date){return getISOYear(date)},H:function(date){return date.getHours()},HH:function(date){return addLeadingZeros(date.getHours(),2)},h:function(date){var hours=date.getHours();return hours===0?12:hours>12?hours%12:hours},hh:function(date){return addLeadingZeros(formatters.h(date),2)},m:function(date){return date.getMinutes()},mm:function(date){return addLeadingZeros(date.getMinutes(),2)},s:function(date){return date.getSeconds()},ss:function(date){return addLeadingZeros(date.getSeconds(),2)},S:function(date){return Math.floor(date.getMilliseconds()/100)},SS:function(date){return addLeadingZeros(Math.floor(date.getMilliseconds()/10),2)},SSS:function(date){return addLeadingZeros(date.getMilliseconds(),3)},Z:function(date){return formatTimezone(date.getTimezoneOffset(),":")},ZZ:function(date){return formatTimezone(date.getTimezoneOffset())},X:function(date){return Math.floor(date.getTime()/1e3)},x:function(date){return date.getTime()}};function buildFormatFn(formatStr,localeFormatters,formattingTokensRegExp){var array=formatStr.match(formattingTokensRegExp),length=array.length,i,formatter;for(i=0;i<length;i++)formatter=localeFormatters[array[i]]||formatters[array[i]],formatter?array[i]=formatter:array[i]=removeFormattingTokens(array[i]);return function(date){for(var output="",i2=0;i2<length;i2++)array[i2]instanceof Function?output+=array[i2](date,formatters):output+=array[i2];return output}}function removeFormattingTokens(input){return input.match(/\[[\s\S]/)?input.replace(/^\[|]$/g,""):input.replace(/\\/g,"")}function formatTimezone(offset,delimeter){delimeter=delimeter||"";var sign=offset>0?"-":"+",absOffset=Math.abs(offset),hours=Math.floor(absOffset/60),minutes=absOffset%60;return sign+addLeadingZeros(hours,2)+delimeter+addLeadingZeros(minutes,2)}function addLeadingZeros(number,targetLength){for(var output=Math.abs(number).toString();output.length<targetLength;)output="0"+output;return output}module.exports=format}});export{require_format};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{getEnvTargetPlaceholder}from"./chunk-LJBUJ23M.js";import{deploymentOption,environmentOption,gitBranchOption,projectOption,targetOption,yesOption}from"./chunk-AWMQGOS2.js";import{packageName}from"./chunk-JESNVRVR.js";var buildCommand={name:"build",aliases:[],description:"Build the project.",arguments:[],options:[{name:"prod",description:"Build a production deployment",shorthand:null,type:Boolean,deprecated:!1},{...environmentOption,description:"Environment to build for: production, preview, or a custom environment (default: preview)"},targetOption,{name:"output",description:"Directory where built assets will be written to",shorthand:null,argument:"DIR",type:String,deprecated:!1},{...yesOption,description:"Skip the confirmation prompt about pulling environment variables and project settings when not found locally"},{name:"standalone",description:"Create a standalone build with all dependencies inlined into function output folders",shorthand:null,type:Boolean,deprecated:!1},{...deploymentOption,description:"Deployment ID to pull environment variables from (e.g. dpl_xxx)"},{name:"id",shorthand:null,type:String,deprecated:!0},projectOption],examples:[{name:"Build the project",value:`${packageName} build`},{name:"Build the project in a specific directory",value:`${packageName} build --cwd ./path-to-project`},{name:"Build with deployment-scoped environment variables",value:`${packageName} build --deployment dpl_xxx`}]};var pullCommand={name:"pull",aliases:[],description:"Pull Environment Variables and project settings into .vercel",arguments:[{name:"project-path",required:!1}],options:[{name:"environment",description:"Deployment environment (default: development)",argument:"ENVIRONMENT",shorthand:"e",type:String,deprecated:!1},{...gitBranchOption,description:"Specify the Git branch to pull specific Environment Variables for"},{name:"prod",shorthand:null,type:Boolean,deprecated:!0},{...yesOption,description:"Skip questions when setting up new project using default scope and settings"},projectOption],examples:[{name:"Pull the latest Environment Variables and Project Settings from the cloud",value:`${packageName} pull`},{name:"Pull the latest Environment Variables and Project Settings from the cloud targeting a directory",value:`${packageName} pull ./path-to-project`},{name:"Pull for a specific environment",value:`${packageName} pull --environment=${getEnvTargetPlaceholder()}`},{name:"Pull for a preview feature branch",value:`${packageName} pull --environment=preview --git-branch=feature-branch`},{name:"Pull Environment Variables into an application env file with `vercel env pull`",value:`${packageName} env pull`}]};export{buildCommand,pullCommand};
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{applyEdits,init_main,modify,parse as parse2,printParseErrorCode}from"./chunk-J24BABG4.js";import{init_dist,parse,stringify}from"./chunk-U4Z2MMOF.js";import{external_exports}from"./chunk-2NABMKFV.js";import{require_execa}from"./chunk-BUJITHGZ.js";import{printAlignedLabel}from"./chunk-ADLBLGT3.js";import{output_manager_default}from"./chunk-XP3FT56R.js";import{__toESM}from"./chunk-BZENIQ7N.js";import{join as join2}from"node:path";init_dist();init_main();import{readFile,writeFile,mkdir,copyFile,access,chmod,lstat,stat,link,unlink}from"node:fs/promises";import{isDeepStrictEqual}from"node:util";import{dirname}from"node:path";async function pathExists(path){try{return await access(path),!0}catch{return!1}}async function isFile(path){try{return(await stat(path)).isFile()}catch{return!1}}async function isSymlink(path){try{return(await lstat(path)).isSymbolicLink()}catch{return!1}}async function readFileOrNull(path){try{return await readFile(path,"utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}function isPlainObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)&&Object.getPrototypeOf(value)===Object.prototype}function deepMerge(base,patch){let out={...base};for(let[key,patchValue]of Object.entries(patch)){let baseValue=out[key];isPlainObject(baseValue)&&isPlainObject(patchValue)?out[key]=deepMerge(baseValue,patchValue):out[key]=patchValue}return out}function detectJsonFormatting(text){let eol=text.includes(`\r
|
|
8
|
+
`)?`\r
|
|
9
|
+
`:`
|
|
10
|
+
`,indent=text.match(/^([ \t]+)\S/m)?.[1];return indent?.startsWith(" ")?{eol,insertSpaces:!1,tabSize:1}:{eol,insertSpaces:!0,tabSize:indent?.length||2}}function parseJsonObjectOrNull(current,parse4=JSON.parse){if(!current||!current.trim())return null;let raw;try{raw=parse4(current)}catch(err){throw new Error(`existing file is not valid JSON (${err.message})`)}if(!isPlainObject(raw))throw new Error("existing file is not a JSON object");return raw}function mergeJson(current,patch,parse4=JSON.parse){let raw=parseJsonObjectOrNull(current,parse4);if(!current||raw===null)return`${JSON.stringify(deepMerge({},patch),null,2)}
|
|
11
|
+
`;let merged=deepMerge(raw,patch),modifyOptions=current.trim().includes(`
|
|
12
|
+
`)?{formattingOptions:detectJsonFormatting(current)}:{};try{let text=current,splice=(existing,subPatch,path)=>{for(let[key,patchValue]of Object.entries(subPatch)){let existingValue=existing?.[key];isPlainObject(patchValue)&&isPlainObject(existingValue)?splice(existingValue,patchValue,[...path,key]):isDeepStrictEqual(existingValue,patchValue)||(text=applyEdits(text,modify(text,[...path,key],patchValue,modifyOptions)))}};if(splice(raw,patch,[]),isDeepStrictEqual(parse4(text),merged))return text}catch{}return`${JSON.stringify(merged,null,2)}
|
|
13
|
+
`}function mergeJsonc(current,patch){return mergeJson(current,patch,text=>{let errors=[],value=parse2(text,errors,{allowTrailingComma:!0}),first=errors[0];if(first)throw new Error(`${printParseErrorCode(first.error)} at offset ${first.offset}`);return value})}function patchSatisfied(existing,patch){for(let[key,patchValue]of Object.entries(patch)){let existingValue=isPlainObject(existing)?existing[key]:void 0;if(isPlainObject(patchValue)&&isPlainObject(existingValue)){if(!patchSatisfied(existingValue,patchValue))return!1}else if(!isDeepStrictEqual(existingValue,patchValue))return!1}return!0}function tomlScalar(value){switch(typeof value){case"string":return JSON.stringify(value);case"number":return Number.isFinite(value)?String(value):null;case"boolean":return String(value);default:return null}}var TOML_BARE_KEY=/^[A-Za-z0-9_-]+$/;function flattenTomlPatch(patch,prefix="",out=new Map){for(let[key,value]of Object.entries(patch)){if(!TOML_BARE_KEY.test(key))return null;if(isPlainObject(value)){if(!flattenTomlPatch(value,prefix?`${prefix}.${key}`:key,out))return null}else{let scalar=tomlScalar(value);if(scalar===null)return null;let section=out.get(prefix);section||(section=new Map,out.set(prefix,section)),section.set(key,scalar)}}return out}var TOML_HEADER=/^\s*\[\[?\s*([^\]]*?)\s*\]\]?\s*(?:#.*)?$/;function mergeToml(current,patch){let parsed={};if(current&¤t.trim())try{parsed=parse(current)}catch(err){throw new Error(`existing file is not valid TOML (${err.message})`)}let legacy=()=>`${stringify(deepMerge(parsed,patch))}
|
|
14
|
+
`;if(!current||!current.trim())return legacy();if(patchSatisfied(parsed,patch))return current;let flat=flattenTomlPatch(patch);if(!flat)return legacy();let crlf=current.includes(`\r
|
|
15
|
+
`),lines=current.split(`
|
|
16
|
+
`),content=line=>line.endsWith("\r")?line.slice(0,-1):line,finish=(line,i)=>i<lines.length&&lines[i]?.endsWith("\r")?`${line}\r`:line,headerAt=i=>{let m=content(lines[i]).match(TOML_HEADER);return m?m[1].split(".").map(s=>s.trim()).join("."):null},sectionRange=name=>{let start=name===""?0:-1;for(let i=0;i<lines.length;i++){let header=headerAt(i);if(header!==null){if(start!==-1)return[start,i];if(name==="")return[0,i];header===name&&(start=i+1)}}return start===-1?null:[start,lines.length]},appendSections=[];for(let[name,keys]of flat){let range=sectionRange(name);if(!range){appendSections.push(`[${name}]`,...[...keys].map(([k,v])=>`${k} = ${v}`));continue}let[start,end]=range,inserts=[];for(let[key,value]of keys){let assignment=new RegExp(`^(\\s*)${key}\\s*=`),replaced=!1;for(let i=start;i<end;i++){let m=content(lines[i]).match(assignment);if(m){lines[i]=finish(`${m[1]}${key} = ${value}`,i),replaced=!0;break}}replaced||inserts.push(`${key} = ${value}`)}if(inserts.length>0){let at=start;for(let i=start;i<end;i++)content(lines[i]).trim()!==""&&(at=i+1);lines.splice(at,0,...inserts.map(l=>finish(l,at)))}}if(appendSections.length>0){for(;lines.length>0&&content(lines[lines.length-1]).trim()==="";)lines.pop();let eol=crlf?"\r":"";lines.push(...["",...appendSections,""].map(l=>l===""?l:`${l}${eol}`))}let result=lines.join(`
|
|
17
|
+
`);try{if(isDeepStrictEqual(parse(result),deepMerge(parsed,patch)))return result}catch{}return legacy()}var MANAGED_BLOCK_START="# >>> vercel ai-gateway >>>",MANAGED_BLOCK_END="# <<< vercel ai-gateway <<<";function upsertManagedBlock(current,body){let block=`${MANAGED_BLOCK_START}
|
|
18
|
+
${body}
|
|
19
|
+
${MANAGED_BLOCK_END}`,existing=current??"",start=existing.indexOf(MANAGED_BLOCK_START),end=existing.indexOf(MANAGED_BLOCK_END);if(start!==-1&&end!==-1&&end>start){let before=existing.slice(0,start),after=existing.slice(end+MANAGED_BLOCK_END.length);return`${before}${block}${after}`}if(existing.length===0)return`${block}
|
|
20
|
+
`;let prefix=existing.endsWith(`
|
|
21
|
+
|
|
22
|
+
`)?"":existing.endsWith(`
|
|
23
|
+
`)?`
|
|
24
|
+
`:`
|
|
25
|
+
|
|
26
|
+
`;return`${existing}${prefix}${block}
|
|
27
|
+
`}async function publishNoClobber(temporary,destination){try{return await link(temporary,destination),!0}catch(error){if(error.code==="EEXIST")return!1;throw error}finally{await unlink(temporary).catch(()=>{})}}async function ensureMode(path,mode){try{await chmod(path,mode)}catch{}}async function backupFile(path,mode){let backupPath=`${path}.bak`;return mode===void 0?(await copyFile(path,backupPath),backupPath):(await ensureMode(backupPath,mode),await writeFile(backupPath,await readFile(path,"utf8"),{mode}),backupPath)}async function writeConfigFile(path,content,mode){await mkdir(dirname(path),{recursive:!0}),mode!==void 0&&await ensureMode(path,mode),await writeFile(path,content,mode===void 0?"utf8":{mode})}var GATEWAY_ANTHROPIC_BASE_URL="https://ai-gateway.vercel.sh",GATEWAY_CODING_AGENT_BASE_URL="https://ai-gateway.vercel.sh/coding-agent/v1",GATEWAY_CURSOR_BASE_URL="https://ai-gateway.vercel.sh/cursor/v1",GATEWAY_CODEX_BASE_URL="https://ai-gateway.vercel.sh/codex/v1",GATEWAY_CLAUDE_CODE_BASE_URL="https://ai-gateway.vercel.sh/claude-code",GATEWAY_API_KEY_ENV="AI_GATEWAY_API_KEY",GATEWAY_DEFAULT_MODEL="anthropic/claude-fable-5",KEY_PLACEHOLDER="__AI_GATEWAY_API_KEY__";function resolveGatewayBaseUrl(override,agentDefault){let trimmed=override?.trim();return trimmed||agentDefault}function maskSecret(secret){return secret&&(secret===KEY_PLACEHOLDER||secret.length<=8?"\u2022\u2022\u2022\u2022":`${secret.slice(0,4)}\u2022\u2022\u2022\u2022${secret.slice(-4)}`)}import{randomUUID}from"node:crypto";import*as fs from"node:fs/promises";import{dirname as dirname2,join}from"node:path";var MAX_RECORD_BYTES=1024*1024;function codeSpan(value){return`\`${value.replace(/[`\r\n]/g,"")}\``}var RECORD_PATTERN=/\.json$/;function claudeAppSupportRoot(home){return process.platform==="darwin"?join(home,"Library","Application Support"):process.platform==="win32"?process.env.APPDATA||join(home,"AppData","Roaming"):join(home,".config")}function toGatewayModelId(model){return model.includes("/")?model:`anthropic/${model}`}async function listSubdirectories(path){try{return(await fs.readdir(path,{withFileTypes:!0})).filter(e=>e.isDirectory()).map(e=>e.name)}catch{return[]}}async function findDestinationIdentity(root){let best=null;for(let account of await listSubdirectories(root))for(let org of await listSubdirectories(join(root,account))){let path=join(root,account,org);try{let stat4=await fs.stat(path);(!best||stat4.mtimeMs>best.mtime)&&(best={path,mtime:stat4.mtimeMs})}catch{}}return best?.path??null}async function readRecord(path){let stat4;try{stat4=await fs.stat(path)}catch{return null}if(!stat4.isFile()||stat4.size>MAX_RECORD_BYTES)return null;try{let raw=await fs.readFile(path,"utf8"),record=JSON.parse(raw);return typeof record!="object"||record===null||Array.isArray(record)?null:{record,bytes:stat4.size}}catch{return null}}async function writeRecordNoClobber(destination,contents){if(await pathExists(destination))return"skipped";await fs.mkdir(dirname2(destination),{recursive:!0});let temp=join(dirname2(destination),`.migrate-${randomUUID()}.tmp`);return await fs.writeFile(temp,contents,{mode:384}),await publishNoClobber(temp,destination)?"copied":"skipped"}async function planClaudeDesktopSessionMigration(home,appSupportRoot=claudeAppSupportRoot(home)){let subscriptionRoot=join(appSupportRoot,"Claude","claude-code-sessions"),gatewayRoot=join(appSupportRoot,"Claude-3p","claude-code-sessions"),destinationDir=await findDestinationIdentity(gatewayRoot);if(!destinationDir)return null;let copies=[],totalBytes=0;for(let account of await listSubdirectories(subscriptionRoot))for(let org of await listSubdirectories(join(subscriptionRoot,account))){let identityDir=join(subscriptionRoot,account,org),names;try{names=await fs.readdir(identityDir)}catch{continue}for(let name of names){if(!RECORD_PATTERN.test(name))continue;let source=join(identityDir,name),destination=join(destinationDir,name);if(await pathExists(destination))continue;let read=await readRecord(source);read&&(copies.push({source,destination,bytes:read.bytes}),totalBytes+=read.bytes)}}return copies.length===0?null:{label:"Claude Desktop sessions",itemCount:copies.length,totalBytes,sourceRoots:[subscriptionRoot],destinationRoots:[destinationDir],prompt:[`Copy the ${copies.length} Claude Desktop session record${copies.length===1?"":"s"} (per-session \`.json\` files) under ${codeSpan(subscriptionRoot)} into ${codeSpan(destinationDir)}, keeping each filename.`,"In each copy, rewrite the top-level `model` field to its AI Gateway id by prefixing `anthropic/` when the value has no provider prefix (e.g. `claude-opus-4-8` \u2192 `anthropic/claude-opus-4-8`); keep any suffix such as `[1m]` intact. Leave every other field unchanged.","Use atomic, no-clobber writes with mode 0600; skip records whose destination already exists. Never move, edit, delete, or overwrite an original record."],async apply(){let copied=0,skipped=0,errors=[];for(let copy of copies)try{let read=await readRecord(copy.source);if(!read){skipped+=1;continue}let record={...read.record};typeof record.model=="string"&&(record.model=toGatewayModelId(record.model)),await writeRecordNoClobber(copy.destination,`${JSON.stringify(record)}
|
|
28
|
+
`)==="copied"?copied+=1:skipped+=1}catch(error){errors.push(`${copy.source}: ${error instanceof Error?error.message:String(error)}`)}return errors.length>0?{copied,skipped,errors}:{copied,skipped}}}}function claudeDir(home){let dir=process.env.CLAUDE_CONFIG_DIR;return dir&&dir.trim()?dir:join2(home,".claude")}var claudeCode={id:"claude-code",displayName:"Claude Code",sessionMigration:{plan:({home})=>planClaudeDesktopSessionMigration(home)},async detect(home){return pathExists(claudeDir(home))},configPath(ctx){return ctx.overrides?.["claude-code"]??join2(claudeDir(ctx.home),"settings.json")},buildPlan(ctx){let path=this.configPath(ctx),env={ANTHROPIC_BASE_URL:resolveGatewayBaseUrl(ctx.baseUrlOverride,GATEWAY_CLAUDE_CODE_BASE_URL),ANTHROPIC_API_KEY:"",CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY:"1",ENABLE_TOOL_SEARCH:"true"},envExports=[];return ctx.useKeychain?envExports.push({name:"ANTHROPIC_AUTH_TOKEN",value:ctx.apiKey}):env.ANTHROPIC_AUTH_TOKEN=ctx.apiKey,{fileChanges:[{path,label:"Claude Code settings",format:"json",...ctx.useKeychain?{}:{mode:384},transform:current=>mergeJson(current,{env})}],envExports,notes:[...ctx.useKeychain?["The Anthropic auth token is read from your shell environment (Keychain-backed).","Open a new terminal so ANTHROPIC_AUTH_TOKEN is loaded, then restart Claude Code."]:["Restart Claude Code to pick up the new settings."],"The Claude Desktop app switches providers in its own settings (Developer \u2192 Configure Third-Party Inference\u2026). After its first gateway launch, re-run this command to copy your existing desktop sessions over."]}}};import{readFile as readFile3,writeFile as writeFile3}from"node:fs/promises";import{access as access2}from"node:fs/promises";import{join as join3}from"node:path";import{homedir}from"node:os";import{spawn}from"node:child_process";var PREFS_FILE="agent-preferences.json",CLAUDE_LEGACY_PLUGIN_ID="vercel-plugin@vercel",CLAUDE_OFFICIAL_MARKETPLACE="claude-plugins-official",CLAUDE_OFFICIAL_MARKETPLACE_SOURCE="anthropics/claude-plugins-official",CLAUDE_OFFICIAL_PLUGIN_ID=`vercel@${CLAUDE_OFFICIAL_MARKETPLACE}`,CLAUDE_DIRECTORY_PLUGIN_ID="vercel@anthropic-plugin-directory",VERCEL_PLUGIN_VERSION_URL="https://raw.githubusercontent.com/vercel/vercel-plugin/main/.claude-plugin/plugin.json",promptedAtSchema=external_exports.codec(external_exports.union([external_exports.iso.date(),external_exports.iso.datetime()]),external_exports.date(),{decode:value=>new Date(value),encode:value=>value.toISOString()}),agentPreferencesSchema=external_exports.object({pluginDeclined:external_exports.boolean().optional(),pluginAutoUpdate:external_exports.boolean().optional(),lastPromptedAt:promptedAtSchema.optional(),lastPluginAutoUpdateAttemptedAt:promptedAtSchema.optional(),lastPluginAutoUpdateAttemptedKey:external_exports.string().optional()});async function fileExists(filePath){try{return await access2(filePath),!0}catch{return!1}}async function readPrefs(client){return await client.maybeReadConfig(PREFS_FILE,agentPreferencesSchema)??{}}async function writePrefs(client,prefs){try{await client.writeConfig(PREFS_FILE,agentPreferencesSchema,prefs)}catch{}}async function getSavedPluginAnswer(client){let{pluginDeclined}=await readPrefs(client);return pluginDeclined===void 0?void 0:!pluginDeclined}async function savePluginAnswer(client,accepted){let prefs=await readPrefs(client);prefs.pluginDeclined=!accepted,prefs.pluginAutoUpdate=accepted,await markPromptedToday(client,prefs)}async function hasClaudeVercelPlugin(home){return(await readClaudeInstalledPluginsFromRegistry(join3(claudeDir(home),"plugins","installed_plugins.json"))).some(plugin=>plugin.id===CLAUDE_OFFICIAL_PLUGIN_ID||plugin.id===CLAUDE_DIRECTORY_PLUGIN_ID)}async function readClaudeInstalledPluginsFromRegistry(registryPath=getClaudeInstalledPluginsRegistryPath()){try{let raw=await readFile3(registryPath,"utf-8"),plugins=JSON.parse(raw)?.plugins??{},entries=[];for(let[id,installs]of Object.entries(plugins))if(Array.isArray(installs))for(let install of installs)!install||typeof install!="object"||entries.push({id,...install,enabled:!0});return entries}catch{return[]}}function getClaudeInstalledPluginsRegistryPath(){return join3(homedir(),".claude","plugins","installed_plugins.json")}async function markStaleClaudePluginInstalls(plugins){return Promise.all(plugins.map(async plugin=>plugin.installPath&&!await fileExists(plugin.installPath)?{...plugin,stale:!0}:plugin))}async function removeClaudePluginFromRegistry(pluginId){try{let registryPath=getClaudeInstalledPluginsRegistryPath(),raw=await readFile3(registryPath,"utf-8"),data=JSON.parse(raw);return!data.plugins||!(pluginId in data.plugins)?!1:(delete data.plugins[pluginId],await writeFile3(registryPath,`${JSON.stringify(data,null,2)}
|
|
29
|
+
`,"utf-8"),!0)}catch(err){return output_manager_default.debug(`Failed to remove Claude plugin registry entry: ${err}`),!1}}async function markPromptedToday(client,prefs){prefs.lastPromptedAt=new Date,await writePrefs(client,prefs)}async function runCommand(command,args){return await new Promise(resolve=>{let child=spawn(command,args,{stdio:"pipe"}),stdout="",stderr="";child.stdout.on("data",chunk=>{stdout+=chunk.toString()}),child.stderr.on("data",chunk=>{stderr+=chunk.toString()}),child.on("close",code=>{resolve({exitCode:code??1,stdout,stderr})}),child.on("error",err=>{resolve({exitCode:1,stdout,stderr:`${stderr}${String(err)}`})})})}async function getClaudeInstalledPlugins(){let result=await runCommand("claude",["plugins","list","--json"]);if(result.exitCode===0)try{let parsed=JSON.parse(result.stdout);if(Array.isArray(parsed))return markStaleClaudePluginInstalls(parsed)}catch(err){output_manager_default.debug(`Failed to parse Claude plugin list JSON: ${err}`)}else result.stderr.trim().length>0&&output_manager_default.debug(`Failed to run 'claude plugins list --json': ${result.stderr}`);return markStaleClaudePluginInstalls(await readClaudeInstalledPluginsFromRegistry())}async function fetchLatestVercelPluginVersion(){try{let response=await fetch(VERCEL_PLUGIN_VERSION_URL);if(!response.ok){output_manager_default.debug(`Failed to fetch latest Vercel plugin version: ${response.status}`);return}let manifest=await response.json();return typeof manifest.version=="string"?manifest.version:void 0}catch(err){output_manager_default.debug(`Failed to fetch latest Vercel plugin version: ${err}`);return}}function comparePluginVersions(a,b){if(!a&&!b)return 0;if(!a)return-1;if(!b)return 1;let parse4=value=>value.split(".").map(part=>Number.parseInt(part,10)||0),left=parse4(a),right=parse4(b),maxLength=Math.max(left.length,right.length);for(let i=0;i<maxLength;i++){let l=left[i]??0,r=right[i]??0;if(l>r)return 1;if(l<r)return-1}return 0}function buildClaudePluginStatus(installedPlugins,latestVersion){let legacy=installedPlugins.find(plugin=>plugin.id===CLAUDE_LEGACY_PLUGIN_ID),official=installedPlugins.find(plugin=>plugin.id===CLAUDE_OFFICIAL_PLUGIN_ID),state="none";return legacy&&official?state="both":legacy?state="legacy-only":official&&(state="official-only"),{state,legacy,official,latestVersion}}function buildClaudePluginMigrationPlan(status){let plan={installOfficial:!1,updateOfficial:!1,removeLegacy:!1,removeLegacyMarketplace:!1};switch(status.state){case"none":plan.installOfficial=!0;break;case"legacy-only":plan.installOfficial=!0,plan.removeLegacy=!0,plan.removeLegacyMarketplace=!0;break;case"both":plan.removeLegacy=!0,plan.removeLegacyMarketplace=!0;break;case"official-only":break}return status.official?.version&&status.latestVersion&&comparePluginVersions(status.official.version,status.latestVersion)<0&&(plan.updateOfficial=!0),plan}function hasClaudeMigrationActions(plan){return plan.installOfficial||plan.updateOfficial||plan.removeLegacy||plan.removeLegacyMarketplace}function buildClaudePromptCopy(status,plan){if(plan.installOfficial&&status.state==="none")return{message:"Vercel Plugin for Claude Code is not installed.",confirm:"Would you like to install it now?"};if(plan.installOfficial&&status.state==="legacy-only")return{message:"Update available for Vercel Plugin for Claude Code (legacy -> official).",confirm:"Would you like to update now?"};if(status.state==="both"&&plan.removeLegacy)return{message:"Vercel Plugin for Claude Code has a legacy install to clean up.",confirm:"Would you like to update now?"};if(plan.updateOfficial){let fromVersion=status.official?.version,toVersion=status.latestVersion;return{message:`Update available for Vercel Plugin for Claude Code${fromVersion&&toVersion?` (v${fromVersion} -> v${toVersion})`:""}.`,confirm:"Would you like to update now?"}}return{message:"The Vercel plugin needs attention in Claude Code before your agent harness is fully up to date.",confirm:"Apply the Vercel plugin changes for Claude Code?"}}async function runClaudeCommand(spinnerMessage,successMessage,failureMessage,args,options){output_manager_default.spinner(spinnerMessage);let result=await runCommand("claude",args);return output_manager_default.stopSpinner(),result.exitCode===0?(options?.quietSuccess||output_manager_default.success(successMessage),!0):(output_manager_default.warn(failureMessage),output_manager_default.debug(`Claude command failed: claude ${args.join(" ")}
|
|
30
|
+
${result.stderr||result.stdout}`),!1)}async function ensureClaudeOfficialMarketplace(){let result=await runCommand("claude",["plugins","marketplace","list","--json"]),marketplaces;try{marketplaces=JSON.parse(result.stdout)}catch{}if(result.exitCode!==0||!Array.isArray(marketplaces))return output_manager_default.debug(`Failed to list Claude plugin marketplaces: ${result.stderr||result.stdout}`),!0;if(marketplaces.some(marketplace=>marketplace?.name===CLAUDE_OFFICIAL_MARKETPLACE))return!0;let added=await runClaudeCommand("Adding the official Claude plugin marketplace...","Added the official Claude plugin marketplace","Failed to add the official Claude plugin marketplace.",["plugins","marketplace","add",CLAUDE_OFFICIAL_MARKETPLACE_SOURCE],{quietSuccess:!0});return added||output_manager_default.log(`Setup command: claude plugins marketplace add ${CLAUDE_OFFICIAL_MARKETPLACE_SOURCE}`),added}async function removeStaleLegacyClaudePlugin(removeMarketplace){output_manager_default.spinner("Removing the stale legacy Vercel Claude plugin...");let removedRegistryEntry=await removeClaudePluginFromRegistry(CLAUDE_LEGACY_PLUGIN_ID);if(output_manager_default.stopSpinner(),!removedRegistryEntry)return output_manager_default.warn("Could not remove the stale legacy Vercel Claude plugin registry entry."),{removedPlugin:!1,complete:!1};if(output_manager_default.success("Removed the stale legacy Vercel Claude plugin"),removeMarketplace){let removedMarketplace=await runClaudeCommand("Removing the legacy Vercel marketplace...","Removed the legacy Vercel marketplace","Removed the stale legacy Vercel plugin, but could not remove the legacy marketplace.",["plugins","marketplace","remove","vercel"],{quietSuccess:!0});return removedMarketplace||output_manager_default.log("Cleanup command: claude plugins marketplace remove vercel"),{removedPlugin:!0,complete:removedMarketplace}}return{removedPlugin:!0,complete:!0}}async function runClaudeMigration(plan){let removedStaleLegacy=!1,complete=!0;if(plan.removeLegacy&&(await getClaudePluginStatus()).legacy?.stale){let cleanup=await removeStaleLegacyClaudePlugin(plan.removeLegacyMarketplace);removedStaleLegacy=cleanup.removedPlugin,complete=cleanup.complete}if(plan.installOfficial){if(!await ensureClaudeOfficialMarketplace()||!await runClaudeCommand("Installing the official Vercel Claude plugin...","Updated the Vercel plugin","Failed to install the official Vercel Claude plugin.",["plugins","install",CLAUDE_OFFICIAL_PLUGIN_ID]))return!1}else if(plan.updateOfficial&&!await runClaudeCommand("Updating the official Vercel Claude plugin...","Updated the Vercel plugin","Failed to update the official Vercel Claude plugin.",["plugins","update",CLAUDE_OFFICIAL_PLUGIN_ID]))return!1;let statusAfterInstall=await getClaudePluginStatus();return statusAfterInstall.official?plan.removeLegacy&&statusAfterInstall.legacy&&!await runClaudeCommand("Removing the legacy Vercel Claude plugin...","Removed the legacy Vercel Claude plugin","Installed the official Vercel Claude plugin, but could not remove the legacy install.",["plugins","uninstall",CLAUDE_LEGACY_PLUGIN_ID],{quietSuccess:!0})?(output_manager_default.log(`Cleanup command: claude plugins uninstall ${CLAUDE_LEGACY_PLUGIN_ID}`),!1):plan.removeLegacyMarketplace&&!removedStaleLegacy&&!(await getClaudePluginStatus()).legacy&&!await runClaudeCommand("Removing the legacy Vercel marketplace...","Removed the legacy Vercel marketplace","Removed the legacy Vercel plugin, but could not remove the legacy marketplace.",["plugins","marketplace","remove","vercel"],{quietSuccess:!0})?(output_manager_default.log("Cleanup command: claude plugins marketplace remove vercel"),!1):complete:(output_manager_default.warn("Skipping Claude cleanup because the official Vercel plugin is not installed."),!1)}async function getClaudePluginStatus(){let[installedPlugins,latestVersion]=await Promise.all([getClaudeInstalledPlugins(),fetchLatestVercelPluginVersion()]);return buildClaudePluginStatus(installedPlugins,latestVersion)}function describeClaudePlan(plan){let actions=[];return plan.installOfficial&&actions.push("install the official plugin"),plan.updateOfficial&&actions.push("update the official plugin"),plan.removeLegacy&&actions.push("remove the legacy plugin"),plan.removeLegacyMarketplace&&actions.push("remove the legacy marketplace"),actions.join(", ")}async function setupVercelPlugin(client,opts){if(!await claudeCode.detect(opts.home))return{status:"not_detected",message:"Claude Code was not detected on this machine."};let status=await getClaudePluginStatus();if(status.official?.stale)return{status:"failed",message:"The installed Vercel plugin files are missing. Run `claude plugins uninstall vercel@claude-plugins-official`, then run `vercel setup plugin --agent claude-code` to reinstall it."};let plan=buildClaudePluginMigrationPlan(status);if(!hasClaudeMigrationActions(plan))return{status:"up_to_date",message:`Vercel plugin for Claude Code is installed${status.official?.version?` (v${status.official.version})`:""}.`};let copy=buildClaudePromptCopy(status,plan);if(opts.dryRun)return{status:"dry_run",message:`${copy.message} Setup would ${describeClaudePlan(plan)}.`,action:plan.installOfficial?"install":"update"};let prefs=await readPrefs(client);if(!opts.yes){if(!opts.canPrompt)return{status:"confirmation_required",message:`${copy.message} Re-run with --yes to apply it.`};output_manager_default.print(` ${copy.message}
|
|
31
|
+
`);let accepted=await client.input.confirm(copy.confirm,!0);if(await markPromptedToday(client,prefs),!accepted)return prefs.pluginDeclined=!0,prefs.pluginAutoUpdate=!1,await writePrefs(client,prefs),{status:"declined",message:"Skipped the Vercel plugin for Claude Code."}}prefs.pluginDeclined=!1,prefs.pluginAutoUpdate=!0,await writePrefs(client,prefs);let migrated=await runClaudeMigration(plan),after=await getClaudePluginStatus();if(!after.official)return{status:"failed",message:"Failed to install the Vercel plugin for Claude Code. Run `claude plugins install vercel@claude-plugins-official` to install it manually."};let remaining=buildClaudePluginMigrationPlan({...after,latestVersion:plan.updateOfficial?status.latestVersion:void 0});if(!migrated||after.official.stale||hasClaudeMigrationActions(remaining))return{status:"failed",message:"Failed to complete Vercel plugin setup for Claude Code. Re-run `vercel setup plugin --agent claude-code --yes` to retry."};let version=after.official.version?` v${after.official.version}`:"";return{status:plan.installOfficial?"installed":"updated",message:`${plan.installOfficial?"Installed":"Updated"} the Vercel plugin for Claude Code${version}.`}}var import_execa=__toESM(require_execa(),1);import{join as join5}from"node:path";import{createHash as createHash2,randomUUID as randomUUID2}from"node:crypto";var regex_default=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function validate(uuid){return typeof uuid=="string"&®ex_default.test(uuid)}var validate_default=validate;function parse3(uuid){if(!validate_default(uuid))throw TypeError("Invalid UUID");let v;return Uint8Array.of((v=parseInt(uuid.slice(0,8),16))>>>24,v>>>16&255,v>>>8&255,v&255,(v=parseInt(uuid.slice(9,13),16))>>>8,v&255,(v=parseInt(uuid.slice(14,18),16))>>>8,v&255,(v=parseInt(uuid.slice(19,23),16))>>>8,v&255,(v=parseInt(uuid.slice(24,36),16))/1099511627776&255,v/4294967296&255,v>>>24&255,v>>>16&255,v>>>8&255,v&255)}var parse_default=parse3;var byteToHex=[];for(let i=0;i<256;++i)byteToHex.push((i+256).toString(16).slice(1));function unsafeStringify(arr,offset=0){return(byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]).toLowerCase()}function stringToBytes(str){str=unescape(encodeURIComponent(str));let bytes=new Uint8Array(str.length);for(let i=0;i<str.length;++i)bytes[i]=str.charCodeAt(i);return bytes}var DNS="6ba7b810-9dad-11d1-80b4-00c04fd430c8",URL="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function v35(version,hash,value,namespace,buf,offset){let valueBytes=typeof value=="string"?stringToBytes(value):value,namespaceBytes=typeof namespace=="string"?parse_default(namespace):namespace;if(typeof namespace=="string"&&(namespace=parse_default(namespace)),namespace?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let bytes=new Uint8Array(16+valueBytes.length);if(bytes.set(namespaceBytes),bytes.set(valueBytes,namespaceBytes.length),bytes=hash(bytes),bytes[6]=bytes[6]&15|version,bytes[8]=bytes[8]&63|128,buf){if(offset??=0,offset<0||offset+16>buf.length)throw new RangeError(`UUID byte range ${offset}:${offset+15} is out of buffer bounds`);for(let i=0;i<16;++i)buf[offset+i]=bytes[i];return buf}return unsafeStringify(bytes)}import{createHash}from"node:crypto";function sha1(bytes){return Array.isArray(bytes)?bytes=Buffer.from(bytes):typeof bytes=="string"&&(bytes=Buffer.from(bytes,"utf8")),createHash("sha1").update(bytes).digest()}var sha1_default=sha1;function v5(value,namespace,buf,offset){return v35(80,sha1_default,value,namespace,buf,offset)}v5.DNS=DNS;v5.URL=URL;var v5_default=v5;import{createReadStream,createWriteStream}from"node:fs";import*as fs2 from"node:fs/promises";import{basename,dirname as dirname3,join as join4}from"node:path";import{pipeline}from"node:stream/promises";var ROLLOUT_PATTERN=/^rollout-.*\.jsonl(?:\.zst)?$/,MAX_METADATA_BYTES=1024*1024;function hasCode(error,code){return error.code===code}async function readMeta(path,gateway=!1){let handle=await fs2.open(path,"r"),buffer=new Uint8Array(MAX_METADATA_BYTES+1),length=0,newline=-1;try{for(;length<buffer.length&&newline<0;){let start=length,read=await handle.read(buffer,start,buffer.length-start,start);if(read.bytesRead===0)break;length+=read.bytesRead,newline=buffer.indexOf(10,start)}}finally{await handle.close()}if(newline<0&&length>MAX_METADATA_BYTES)throw new Error(`${basename(path)} metadata exceeds 1 MiB`);let lineEnd=newline<0?length:newline,carriageReturn=buffer[lineEnd-1]===13,record;try{record=JSON.parse(new TextDecoder().decode(buffer.subarray(0,carriageReturn?lineEnd-1:lineEnd)))}catch{return null}let payload=record.payload,id=typeof payload?.id=="string"?payload.id:typeof payload?.session_id=="string"?payload.session_id:"";return record.type!=="session_meta"||!payload||!validate_default(id)||typeof payload.session_id=="string"&&payload.session_id!==id||payload.originator!=="Codex Desktop"&&!(payload.originator==null&&payload.source==="vscode")||(gateway?payload.model_provider!=="vercel":payload.model_provider==="vercel")?null:{record,payload,id,delimiter:newline<0?"":carriageReturn?`\r
|
|
32
|
+
`:`
|
|
33
|
+
`,restOffset:newline<0?length:newline+1}}function codeSpan2(value){return`\`${value.replace(/[`\r\n]/g,"")}\``}async function findRollouts(root){let files=[];async function visit(directory){let entries;try{entries=await fs2.readdir(directory,{withFileTypes:!0})}catch(error){if(hasCode(error,"ENOENT"))return;throw error}for(let entry of entries){let path=join4(directory,entry.name);entry.isDirectory()?await visit(path):entry.isFile()&&ROLLOUT_PATTERN.test(entry.name)&&files.push(path)}}return await visit(root),files}async function planCopy(path,root){let metadata=await readMeta(path),filename=basename(path);if(!metadata||!filename.toLowerCase().includes(metadata.id.toLowerCase()))return null;let destinationId=v5_default(`vercel-ai-gateway/codex/${metadata.id.toLowerCase()}/vercel`,v5_default.URL),destination=join4(dirname3(path),filename.replace(new RegExp(metadata.id,"i"),destinationId)),item={source:path,destination,sourceId:metadata.id,destinationId,bytes:(await fs2.stat(path)).size,root};try{return await fs2.stat(destination),await validateDestination(item),null}catch(error){if(!hasCode(error,"ENOENT"))throw error}return item}async function bodyHash(path,start){let hash=createHash2("sha256");return await pipeline(createReadStream(path,{start}),hash),hash.digest("hex")}async function validateDestination(item){let[source,destination]=await Promise.all([readMeta(item.source),readMeta(item.destination,!0)]),bodies=await Promise.all([bodyHash(item.source,source?.restOffset??0),bodyHash(item.destination,destination?.restOffset??0)]);if(!(source&&destination?.id===item.destinationId&&bodies[0]===bodies[1]))throw new Error(`Existing destination ${basename(item.destination)} is invalid`)}async function copySession(item){let metadata=await readMeta(item.source);if(!metadata)throw new Error("Codex session metadata is no longer valid");if(metadata.id!==item.sourceId)throw new Error("Codex session metadata changed after planning");let updated={...metadata.record,payload:{...metadata.payload,id:item.destinationId,session_id:item.destinationId,model_provider:"vercel"}},temporary=`${item.destination}.tmp-${process.pid}-${randomUUID2()}`;try{return await fs2.writeFile(temporary,`${JSON.stringify(updated)}${metadata.delimiter}`,{flag:"wx",mode:384}),await pipeline(createReadStream(item.source,{start:metadata.restOffset}),createWriteStream(temporary,{flags:"a",mode:384})),await fs2.chmod(temporary,384),await publishNoClobber(temporary,item.destination)?!0:(await validateDestination(item),!1)}finally{await fs2.unlink(temporary).catch(error=>{if(!hasCode(error,"ENOENT"))throw error})}}async function planCodexSessionMigration(home){let codexHome=process.env.CODEX_HOME||join4(home,".codex"),roots=["sessions","archived_sessions"].map(root=>join4(codexHome,root)),files=[];for(let root of roots)files.push(...(await findRollouts(root)).map(path=>({path,root})));if(files.some(file=>file.path.endsWith(".jsonl.zst")))throw new Error("Found compressed Codex sessions; decompress them first, or pass --no-session-migration to leave them unchanged");let copies=[];for(let file of files){let copy=await planCopy(file.path,file.root);copy&&copies.push(copy)}if(copies.length===0)return null;let sourceRoots=[...new Set(copies.map(copy=>copy.root))];return{label:"Codex Desktop sessions",itemCount:copies.length,totalBytes:copies.reduce((total,copy)=>total+copy.bytes,0),sourceRoots,destinationRoots:sourceRoots,prompt:[`Before changing the provider, copy the ${copies.length} top-level Codex Desktop rollout${copies.length===1?"":"s"} with a non-\`vercel\` provider under ${sourceRoots.map(codeSpan2).join(", ")}. Do not copy subagent rollouts whose \`session_id\` differs from \`id\`.`,"For each copy, derive a deterministic UUID v5 using the URL namespace `6ba7b811-9dad-11d1-80b4-00c04fd430c8` and name `vercel-ai-gateway/codex/<source-id>/vercel`. Replace the filename UUID and `session_meta.payload.id`/`session_id`, set `model_provider` to `vercel`, and preserve every later JSONL byte.","Use atomic, no-clobber writes with mode 0600; skip an existing deterministic destination only after validating its metadata and body. Never move, edit, delete, or overwrite an original session file."],async apply(){let copied=0,skipped=0,errors=[];for(let item of copies)try{await copySession(item)?copied++:skipped++}catch(error){errors.push(`${basename(item.source)}: ${error instanceof Error?error.message:String(error)}`)}return{copied,skipped,errors}}}}function codexDir(home){let dir=process.env.CODEX_HOME;return dir&&dir.trim()?dir:join5(home,".codex")}var codex={id:"codex",displayName:"Codex",sessionMigration:{plan:({home})=>planCodexSessionMigration(home)},async detect(home){return pathExists(codexDir(home))},configPath(ctx){return ctx.overrides?.codex??join5(codexDir(ctx.home),"config.toml")},buildPlan(ctx){return{fileChanges:[{path:this.configPath(ctx),label:"Codex config",format:"toml",transform:current=>mergeToml(current,{model_provider:"vercel",model_providers:{vercel:{name:"Vercel AI Gateway",base_url:resolveGatewayBaseUrl(ctx.baseUrlOverride,GATEWAY_CODEX_BASE_URL),env_key:GATEWAY_API_KEY_ENV,wire_api:"responses"}}})}],envExports:[{name:GATEWAY_API_KEY_ENV,value:ctx.apiKey}],notes:["Codex now defaults to the Vercel AI Gateway; pick a model with --model or in config.",`Open a new terminal so ${GATEWAY_API_KEY_ENV} is loaded, or run: export ${GATEWAY_API_KEY_ENV}=<key>`]}}};var MARKETPLACE="openai-curated-remote",PLUGIN_ID=`vercel@${MARKETPLACE}`,INSTALL_COMMAND=`codex plugin add ${PLUGIN_ID}`,SIGN_IN_MESSAGE="Can't install the Vercel plugin for Codex without a ChatGPT sign-in. Run `codex login`, then `vercel setup plugin --agent codex`.",pluginListSchema=external_exports.object({installed:external_exports.array(external_exports.object({pluginId:external_exports.string(),enabled:external_exports.boolean(),version:external_exports.string().nullable().optional()}))});async function runCodex(args){let{stdout}=await(0,import_execa.default)("codex",args,{encoding:"utf8",stdin:"ignore",timeout:6e4,maxBuffer:1048576});return stdout}function needsChatGptSignIn(err){let{message,stderr}=err;return[message,stderr].some(text=>typeof text=="string"&&/chatgpt authentication required/i.test(text))}async function installedPlugin(){let stdout=await runCodex(["plugin","list","--marketplace",MARKETPLACE,"--json"]),{installed}=pluginListSchema.parse(JSON.parse(stdout));return installed.find(plugin=>plugin.pluginId===PLUGIN_ID)}async function setupCodexPlugin(client,opts){if(!await codex.detect(opts.home))return{status:"not_detected",message:"Codex was not detected on this machine."};let before;try{before=await installedPlugin()}catch(err){return{status:"failed",message:needsChatGptSignIn(err)?SIGN_IN_MESSAGE:"Couldn't inspect Codex plugins. Install or update the Codex CLI, sign in with `codex login`, then re-run `vercel setup plugin --agent codex`."}}if(before?.enabled)return{status:"up_to_date",message:`Vercel plugin for Codex is installed${before.version?` (v${before.version})`:""}.`};let action=before?"enable":"install";if(opts.dryRun)return{status:"dry_run",action,message:`Setup would ${action} the Vercel plugin for Codex from the OpenAI marketplace.`};if(!opts.yes){if(!opts.canPrompt)return{status:"confirmation_required",message:`Re-run with --yes to ${action} the Vercel plugin for Codex.`};if(printAlignedLabel("Plugin","Vercel for Codex (OpenAI marketplace)"),!await client.input.confirm(before?"Enable this plugin?":"Install this plugin?",!0))return{status:"declined",message:"Skipped the Vercel plugin for Codex."}}output_manager_default.spinner(`${before?"Enabling":"Installing"} the Vercel plugin for Codex\u2026`);try{let stdout=await runCodex(["plugin","add",PLUGIN_ID,"--json"]),install=external_exports.object({appsNeedingAuth:external_exports.array(external_exports.unknown()).optional()}).parse(JSON.parse(stdout)),after=await installedPlugin();if(!after?.enabled)return{status:"failed",message:"The Vercel plugin is not enabled in Codex. Open Codex's /plugins browser, enable Vercel, then re-run `vercel setup plugin --agent codex`."};let version=after.version?` v${after.version}`:"",connection=install.appsNeedingAuth?.length?" Connect Vercel in Codex's /plugins browser to use its connected tools.":" Start a new Codex session to load the plugin.";return{status:before?"enabled":"installed",message:`${before?"Enabled":"Installed"} the Vercel plugin for Codex${version}.${connection}`}}catch(err){return{status:"failed",message:needsChatGptSignIn(err)?SIGN_IN_MESSAGE:`Failed to set up the Vercel plugin for Codex. Run \`${INSTALL_COMMAND}\` to finish setup in Codex.`}}finally{output_manager_default.stopSpinner()}}export{pathExists,isFile,isSymlink,readFileOrNull,parseJsonObjectOrNull,mergeJson,mergeJsonc,mergeToml,MANAGED_BLOCK_START,MANAGED_BLOCK_END,upsertManagedBlock,ensureMode,backupFile,writeConfigFile,GATEWAY_ANTHROPIC_BASE_URL,GATEWAY_CODING_AGENT_BASE_URL,GATEWAY_CURSOR_BASE_URL,GATEWAY_API_KEY_ENV,GATEWAY_DEFAULT_MODEL,KEY_PLACEHOLDER,resolveGatewayBaseUrl,maskSecret,claudeCode,codex,getSavedPluginAnswer,savePluginAnswer,hasClaudeVercelPlugin,setupVercelPlugin,setupCodexPlugin};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{require_raw_body}from"./chunk-XOETL6DB.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_raw_body=__toESM(require_raw_body(),1);async function readStdinText(stdin,limit){return stdin.isTTY?"":(await(0,import_raw_body.default)(stdin,{limit,encoding:"utf8"})).replace(/\r?\n$/,"")}async function readStandardInput(stdin){return new Promise(resolve=>{setTimeout(()=>resolve(""),500),stdin.isTTY?resolve(""):(stdin.setEncoding("utf8"),stdin.once("data",resolve))})}export{readStdinText,readStandardInput};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{__commonJS}from"./chunk-BZENIQ7N.js";var require_dist=__commonJS({"../../internals/constants/dist/index.js"(exports){"use strict";Object.defineProperty(exports,"__esModule",{value:!0});exports.TITLE=exports.NAME=exports.LOGO=exports.PROJECT_ENV_TARGET=void 0;exports.PROJECT_ENV_TARGET=["production","preview","development"];exports.LOGO="\u25B2";exports.NAME="vercel";exports.TITLE="Vercel"}});export{require_dist};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{__commonJS,__require}from"./chunk-BZENIQ7N.js";var require_is_docker=__commonJS({"../../node_modules/.pnpm/is-docker@2.2.1/node_modules/is-docker/index.js"(exports,module){"use strict";var fs=__require("fs"),isDocker;function hasDockerEnv(){try{return fs.statSync("/.dockerenv"),!0}catch{return!1}}function hasDockerCGroup(){try{return fs.readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return!1}}module.exports=()=>(isDocker===void 0&&(isDocker=hasDockerEnv()||hasDockerCGroup()),isDocker)}});var require_is_wsl=__commonJS({"../../node_modules/.pnpm/is-wsl@2.2.0/node_modules/is-wsl/index.js"(exports,module){"use strict";var os=__require("os"),fs=__require("fs"),isDocker=require_is_docker(),isWsl=()=>{if(process.platform!=="linux")return!1;if(os.release().toLowerCase().includes("microsoft"))return!isDocker();try{return fs.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!isDocker():!1}catch{return!1}};process.env.__IS_WSL_TEST__?module.exports=isWsl:module.exports=isWsl()}});var require_define_lazy_prop=__commonJS({"../../node_modules/.pnpm/define-lazy-prop@2.0.0/node_modules/define-lazy-prop/index.js"(exports,module){"use strict";module.exports=(object,propertyName,fn)=>{let define=value=>Object.defineProperty(object,propertyName,{value,enumerable:!0,writable:!0});return Object.defineProperty(object,propertyName,{configurable:!0,enumerable:!0,get(){let result=fn();return define(result),result},set(value){define(value)}}),object}}});var require_open=__commonJS({"../../node_modules/.pnpm/open@8.4.0/node_modules/open/index.js"(exports,module){var path=__require("path"),childProcess=__require("child_process"),{promises:fs,constants:fsConstants}=__require("fs"),isWsl=require_is_wsl(),isDocker=require_is_docker(),defineLazyProperty=require_define_lazy_prop(),localXdgOpenPath=path.join(__dirname,"xdg-open"),{platform,arch}=process,getWslDrivesMountPoint=(()=>{let defaultMountPoint="/mnt/",mountPoint;return async function(){if(mountPoint)return mountPoint;let configFilePath="/etc/wsl.conf",isConfigFileExists=!1;try{await fs.access(configFilePath,fsConstants.F_OK),isConfigFileExists=!0}catch{}if(!isConfigFileExists)return defaultMountPoint;let configContent=await fs.readFile(configFilePath,{encoding:"utf8"}),configMountPoint=/(?<!#.*)root\s*=\s*(?<mountPoint>.*)/g.exec(configContent);return configMountPoint?(mountPoint=configMountPoint.groups.mountPoint.trim(),mountPoint=mountPoint.endsWith("/")?mountPoint:`${mountPoint}/`,mountPoint):defaultMountPoint}})(),pTryEach=async(array,mapper)=>{let latestError;for(let item of array)try{return await mapper(item)}catch(error){latestError=error}throw latestError},baseOpen=async options=>{if(options={wait:!1,background:!1,newInstance:!1,allowNonzeroExitCode:!1,...options},Array.isArray(options.app))return pTryEach(options.app,singleApp=>baseOpen({...options,app:singleApp}));let{name:app,arguments:appArguments=[]}=options.app||{};if(appArguments=[...appArguments],Array.isArray(app))return pTryEach(app,appName=>baseOpen({...options,app:{name:appName,arguments:appArguments}}));let command,cliArguments=[],childProcessOptions={};if(platform==="darwin")command="open",options.wait&&cliArguments.push("--wait-apps"),options.background&&cliArguments.push("--background"),options.newInstance&&cliArguments.push("--new"),app&&cliArguments.push("-a",app);else if(platform==="win32"||isWsl&&!isDocker()){let mountPoint=await getWslDrivesMountPoint();command=isWsl?`${mountPoint}c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe`:`${process.env.SYSTEMROOT}\\System32\\WindowsPowerShell\\v1.0\\powershell`,cliArguments.push("-NoProfile","-NonInteractive","\u2013ExecutionPolicy","Bypass","-EncodedCommand"),isWsl||(childProcessOptions.windowsVerbatimArguments=!0);let encodedArguments=["Start"];options.wait&&encodedArguments.push("-Wait"),app?(encodedArguments.push(`"\`"${app}\`""`,"-ArgumentList"),options.target&&appArguments.unshift(options.target)):options.target&&encodedArguments.push(`"${options.target}"`),appArguments.length>0&&(appArguments=appArguments.map(arg=>`"\`"${arg}\`""`),encodedArguments.push(appArguments.join(","))),options.target=Buffer.from(encodedArguments.join(" "),"utf16le").toString("base64")}else{if(app)command=app;else{let isBundled=!__dirname||__dirname==="/",exeLocalXdgOpen=!1;try{await fs.access(localXdgOpenPath,fsConstants.X_OK),exeLocalXdgOpen=!0}catch{}command=process.versions.electron||platform==="android"||isBundled||!exeLocalXdgOpen?"xdg-open":localXdgOpenPath}appArguments.length>0&&cliArguments.push(...appArguments),options.wait||(childProcessOptions.stdio="ignore",childProcessOptions.detached=!0)}options.target&&cliArguments.push(options.target),platform==="darwin"&&appArguments.length>0&&cliArguments.push("--args",...appArguments);let subprocess=childProcess.spawn(command,cliArguments,childProcessOptions);return options.wait?new Promise((resolve,reject)=>{subprocess.once("error",reject),subprocess.once("close",exitCode=>{if(options.allowNonzeroExitCode&&exitCode>0){reject(new Error(`Exited with code ${exitCode}`));return}resolve(subprocess)})}):(subprocess.unref(),subprocess)},open=(target,options)=>{if(typeof target!="string")throw new TypeError("Expected a `target`");return baseOpen({...options,target})},openApp=(name,options)=>{if(typeof name!="string")throw new TypeError("Expected a `name`");let{arguments:appArguments=[]}=options||{};if(appArguments!=null&&!Array.isArray(appArguments))throw new TypeError("Expected `appArguments` as Array type");return baseOpen({...options,app:{name,arguments:appArguments}})};function detectArchBinary(binary){if(typeof binary=="string"||Array.isArray(binary))return binary;let{[arch]:archBinary}=binary;if(!archBinary)throw new Error(`${arch} is not supported`);return archBinary}function detectPlatformBinary({[platform]:platformBinary},{wsl}){if(wsl&&isWsl)return detectArchBinary(wsl);if(!platformBinary)throw new Error(`${platform} is not supported`);return detectArchBinary(platformBinary)}var apps={};defineLazyProperty(apps,"chrome",()=>detectPlatformBinary({darwin:"google chrome",win32:"chrome",linux:["google-chrome","google-chrome-stable","chromium"]},{wsl:{ia32:"/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe",x64:["/mnt/c/Program Files/Google/Chrome/Application/chrome.exe","/mnt/c/Program Files (x86)/Google/Chrome/Application/chrome.exe"]}}));defineLazyProperty(apps,"firefox",()=>detectPlatformBinary({darwin:"firefox",win32:"C:\\Program Files\\Mozilla Firefox\\firefox.exe",linux:"firefox"},{wsl:"/mnt/c/Program Files/Mozilla Firefox/firefox.exe"}));defineLazyProperty(apps,"edge",()=>detectPlatformBinary({darwin:"microsoft edge",win32:"msedge",linux:["microsoft-edge","microsoft-edge-dev"]},{wsl:"/mnt/c/Program Files (x86)/Microsoft/Edge/Application/msedge.exe"}));open.apps=apps;open.openApp=openApp;module.exports=open}});export{require_open};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{outputError}from"./chunk-RW3X523R.js";import{canPrompt}from"./chunk-IQ7FPAI4.js";import{readFileSync}from"node:fs";function readAllStandardInput(stdin){return stdin.isTTY?Promise.resolve(""):new Promise(resolve=>{let chunks=[],timer=setTimeout(()=>{chunks.length===0&&(cleanup(),resolve(""))},500),onData=chunk=>{chunks.push(String(chunk))},onEnd=()=>{cleanup(),resolve(chunks.join(""))};function cleanup(){clearTimeout(timer),stdin.off("data",onData),stdin.off("end",onEnd)}stdin.setEncoding("utf8"),stdin.on("data",onData),stdin.on("end",onEnd)})}async function resolveMessageContent(client,flags,jsonOutput){if(flags.message!==void 0&&flags.file!==void 0)return outputError(client,jsonOutput,"CONFLICTING_CONTENT","Use either --message or --file, not both.");if(flags.message!==void 0)return flags.message;if(flags.file!==void 0){if(flags.file==="-"){let piped2=await readAllStandardInput(client.stdin);return piped2||outputError(client,jsonOutput,"MISSING_CONTENT","No content received on stdin for `--file -`.")}try{return readFileSync(flags.file,"utf8")}catch(err){return outputError(client,jsonOutput,"FILE_READ_ERROR",`Could not read ${flags.file}: ${err instanceof Error?err.message:String(err)}`)}}let piped=await readAllStandardInput(client.stdin);if(piped)return piped;if(!flags.hasAttachments){if(canPrompt(client)&&!jsonOutput){let text=await client.input.text({message:"Comment message:"});if(text)return text}return outputError(client,jsonOutput,"MISSING_CONTENT",'No content provided. Pass --message <text>, --file <path>, or pipe stdin (e.g. `echo "LGTM" | vercel comments reply <thread>`).')}}export{resolveMessageContent};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{require_ms}from"./chunk-MXTC4ZAQ.js";import{require_source}from"./chunk-NB2WLB3J.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_ms=__toESM(require_ms(),1),import_chalk=__toESM(require_source(),1);function elapsed(time,ago=!1){return import_chalk.default.gray(`[${time<1e3?`${time}ms`:(0,import_ms.default)(time)}${ago?" ago":""}]`)}export{elapsed};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __dirname_ } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
const __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
const __dirname = __dirname_(__filename);
|
|
7
|
+
import{require_dist2 as require_dist}from"./chunk-7L2K4OKM.js";import{require_frameworks}from"./chunk-6Y2ZL5XJ.js";import{__toESM}from"./chunk-BZENIQ7N.js";var import_frameworks=__toESM(require_frameworks(),1),import_fs_detectors=__toESM(require_dist(),1);import{join}from"path";async function detectProjects(cwd){let fs=new import_fs_detectors.LocalFileSystemDetector(cwd),workspaces=await(0,import_fs_detectors.getWorkspaces)({fs}),detectedProjects=new Map,packagePaths=(await Promise.all(workspaces.map(workspace=>(0,import_fs_detectors.getWorkspacePackagePaths)({fs,workspace})))).flat();return packagePaths.length===0&&packagePaths.push("/"),await Promise.all(packagePaths.map(async p=>{let frameworks=await(0,import_fs_detectors.detectFrameworks)({fs:fs.chdir(join(".",p)),frameworkList:import_frameworks.frameworkList});frameworks.length!==0&&detectedProjects.set(p.slice(1),frameworks)})),detectedProjects}export{detectProjects};
|