@depup/vercel 59.23.2-depup.0 → 60.1.3-depup.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -5
- package/changes.json +4 -4
- package/dist/chunks/add-5INBQVKB.js +8 -0
- package/dist/chunks/add-IEQXYKXU.js +8 -0
- package/dist/chunks/add-QJSYPE26.js +8 -0
- package/dist/chunks/build-Z7KM3GMP.js +7 -0
- package/dist/chunks/{chunk-YGJO25LP.js → chunk-25LSRUTF.js} +1 -1
- package/dist/chunks/{chunk-GTJ2OLYI.js → chunk-2R6NQXTQ.js} +1 -1
- package/dist/chunks/{chunk-6LE44WCK.js → chunk-3B4P7YHO.js} +1 -1
- package/dist/chunks/{chunk-M6A7UH4U.js → chunk-3HLNS2I4.js} +5 -5
- package/dist/chunks/{chunk-73G2MHUX.js → chunk-3MVT26LH.js} +1 -1
- package/dist/chunks/{chunk-J5X5YRBH.js → chunk-3RV2B7D3.js} +1 -1
- package/dist/chunks/{chunk-NBVY237X.js → chunk-5ENY7DSN.js} +1 -1
- package/dist/chunks/{chunk-V6IKQCOT.js → chunk-5U25FWD5.js} +1 -1
- package/dist/chunks/chunk-5UOVEMYX.js +7 -0
- package/dist/chunks/{chunk-UXCTETFN.js → chunk-6NPXWN5F.js} +1 -1
- package/dist/chunks/{chunk-JGPECEYY.js → chunk-7CTHRXTG.js} +1 -1
- package/dist/chunks/{chunk-SOQ5DE44.js → chunk-7QVVD3WT.js} +1 -1
- package/dist/chunks/{chunk-ZKWM4JBE.js → chunk-AP36GAOG.js} +1 -1
- package/dist/chunks/{chunk-QI3JSWD6.js → chunk-B6PMTBCU.js} +1 -1
- package/dist/chunks/{chunk-GR3DLKYP.js → chunk-BEGUGOL7.js} +1 -1
- package/dist/chunks/{chunk-HOYHUMBD.js → chunk-BHVHQKUZ.js} +1 -1
- package/dist/chunks/{chunk-QR7QPUFN.js → chunk-BKV35LVB.js} +1 -1
- package/dist/chunks/{chunk-GHULCYAR.js → chunk-C5KVTG2O.js} +1 -1
- package/dist/chunks/chunk-CN4SCEIP.js +7 -0
- package/dist/chunks/chunk-D2ZPYXZ6.js +7 -0
- package/dist/chunks/chunk-DKV4IVH5.js +7 -0
- package/dist/chunks/{chunk-KXYR43H5.js → chunk-DV4Z4WSD.js} +1 -1
- package/dist/chunks/{chunk-6SA6SOHU.js → chunk-E3EJLJFQ.js} +1 -1
- package/dist/chunks/{chunk-EQP3SW72.js → chunk-FZKWLGRG.js} +1 -1
- package/dist/chunks/{chunk-66RYR2GI.js → chunk-GL7HB5ZK.js} +1 -1
- package/dist/chunks/chunk-H4FTGLWV.js +22 -0
- package/dist/chunks/{chunk-E4X2DH4K.js → chunk-HJ3E752K.js} +1 -1
- package/dist/chunks/{chunk-VIR3KDCQ.js → chunk-I46LFJJG.js} +1 -1
- package/dist/chunks/{chunk-TJKM3345.js → chunk-IS43O66T.js} +1 -1
- package/dist/chunks/{chunk-PS645CWM.js → chunk-JM3BFUXX.js} +1 -1
- package/dist/chunks/{chunk-KBKN7EI7.js → chunk-JSKGZLE4.js} +1 -1
- package/dist/chunks/chunk-JZUVWAOK.js +8 -0
- package/dist/chunks/chunk-KCARCOP5.js +10 -0
- package/dist/chunks/chunk-KOOED3TJ.js +9 -0
- package/dist/chunks/chunk-LAYFSD5A.js +7 -0
- package/dist/chunks/chunk-LFQTA3CF.js +7 -0
- package/dist/chunks/{chunk-UWZ5VIIQ.js → chunk-M5Y335WI.js} +1 -1
- package/dist/chunks/{chunk-NYOQMU3P.js → chunk-MDZ2JJP3.js} +4 -4
- package/dist/chunks/{chunk-RRQTVE2P.js → chunk-MKY5IBKK.js} +1 -1
- package/dist/chunks/chunk-N5AIKGEO.js +9 -0
- package/dist/chunks/{chunk-2HEC5TDU.js → chunk-NR367IWV.js} +1 -1
- package/dist/chunks/{chunk-Z7PBDQNR.js → chunk-OCWSKPV4.js} +2 -2
- package/dist/chunks/chunk-QFPCR4NL.js +7 -0
- package/dist/chunks/{chunk-Z6LKARXP.js → chunk-QLS2XUFL.js} +1 -1
- package/dist/chunks/{chunk-GGNZLN4R.js → chunk-QVAZWF3J.js} +1 -1
- package/dist/chunks/{chunk-FZH7RIRX.js → chunk-R7ZRVA7E.js} +2 -2
- package/dist/chunks/chunk-RINZXCDJ.js +19 -0
- package/dist/chunks/{chunk-GL2AUBAI.js → chunk-RMYQX7NP.js} +1 -1
- package/dist/chunks/{chunk-EHTHHCNG.js → chunk-RYZ5FAUA.js} +1 -0
- package/dist/chunks/{chunk-V5DCSHYJ.js → chunk-SM5JI6QM.js} +1 -1
- package/dist/chunks/chunk-SW7MNF4H.js +7 -0
- package/dist/chunks/{chunk-4YVA7TSY.js → chunk-TAG2AZXS.js} +1 -1
- package/dist/chunks/{chunk-64NJHVA3.js → chunk-TTKDYUJD.js} +5 -5
- package/dist/chunks/{chunk-ZDORSGCG.js → chunk-TTMLSKF7.js} +1 -1
- package/dist/chunks/{chunk-UUM2N6IG.js → chunk-U6AYMUHX.js} +2 -2
- package/dist/chunks/{chunk-2SLHYWMC.js → chunk-UFZ4W2PA.js} +1 -1
- package/dist/chunks/{chunk-WDVSYGZS.js → chunk-UO2ECTIU.js} +1 -1
- package/dist/chunks/{chunk-EIXOJUNN.js → chunk-UTVDFSQS.js} +1 -1
- package/dist/chunks/{chunk-SFTXBTMI.js → chunk-V54UKUGF.js} +1 -1
- package/dist/chunks/{chunk-NZKBBY2A.js → chunk-VCB6KNW3.js} +1 -1
- package/dist/chunks/chunk-W26LLGQV.js +7 -0
- package/dist/chunks/{chunk-7B5NNJ2P.js → chunk-WH6M54KF.js} +1 -1
- package/dist/chunks/chunk-WSZHNPA6.js +7 -0
- package/dist/chunks/{chunk-T4AZ3U7O.js → chunk-WWB66KP5.js} +1 -1
- package/dist/chunks/{chunk-4WSAOLBH.js → chunk-XQQGQ55A.js} +1 -1
- package/dist/chunks/{chunk-6LE3FU2P.js → chunk-Y7PHTVZ6.js} +1 -1
- package/dist/chunks/chunk-YJZFFNUB.js +27 -0
- package/dist/chunks/chunk-YXBDDHPL.js +9 -0
- package/dist/chunks/{chunk-UGXNE4YE.js → chunk-YXTE2H6I.js} +1 -1
- package/dist/chunks/clear-AZWSIGIF.js +8 -0
- package/dist/chunks/compile-vercel-config-56X2X4Z3.js +7 -0
- package/dist/chunks/config-A53AXEGB.js +7 -0
- package/dist/chunks/config-NGVEJABO.js +8 -0
- package/dist/chunks/config-validator.mjs +1 -1
- package/dist/chunks/{connect-git-provider-P3SGOW6X.js → connect-git-provider-VYU65KTS.js} +1 -1
- package/dist/chunks/delete-LX44AJYC.js +10 -0
- package/dist/chunks/delete-TA6UVDSJ.js +9 -0
- package/dist/chunks/{detect-projects-WLAFT5HC.js → detect-projects-LEVGWMQE.js} +1 -1
- package/dist/chunks/detect-services-KO3GQ2ZK.js +7 -0
- package/dist/chunks/disable-E7TU3QIX.js +7 -0
- package/dist/chunks/discard-SVF5HBYG.js +14 -0
- package/dist/chunks/edit-2RLFRAOJ.js +8 -0
- package/dist/chunks/edit-VCOF42GW.js +9 -0
- package/dist/chunks/enable-H6RL2XIW.js +7 -0
- package/dist/chunks/{exec-YH5WUJ4C.js → exec-3RMS2X6B.js} +1 -1
- package/dist/chunks/{export-QCBAQNTT.js → export-JW3FFP7N.js} +1 -1
- package/dist/chunks/future-IGDV62BF.js +7 -0
- package/dist/chunks/generate-cert-for-deploy-25UQ2477.js +7 -0
- package/dist/chunks/{image-DU7GJZR2.js → image-MHAVMOJB.js} +1 -1
- package/dist/chunks/import-builders-5UODCCVF.js +7 -0
- package/dist/chunks/{inspect-IVJOEZC4.js → inspect-43UJHR4K.js} +1 -1
- package/dist/chunks/{inspect-EMWJLBAW.js → inspect-HJF2XFBX.js} +1 -1
- package/dist/chunks/{inspect-CPOFKE4X.js → inspect-KBJ7F64J.js} +1 -1
- package/dist/chunks/inspect-LIGFVYDM.js +13 -0
- package/dist/chunks/inspect-VETXDYUD.js +9 -0
- package/dist/chunks/{list-KYZNCXBM.js → list-EGYYRTG5.js} +1 -1
- package/dist/chunks/list-KAGIR3PD.js +11 -0
- package/dist/chunks/{list-ZE2VPPXI.js → list-NAABRL7N.js} +1 -1
- package/dist/chunks/login-MZ67I5ZB.js +9 -0
- package/dist/chunks/login-X3KPMMEP.js +7 -0
- package/dist/chunks/logs-GHHH2DZA.js +7 -0
- package/dist/chunks/{ls-AKGRKWHM.js → ls-7JFKEA5P.js} +1 -1
- package/dist/chunks/ls-GOLB26ER.js +11 -0
- package/dist/chunks/{ls-7O63WIES.js → ls-JHJPWFMF.js} +1 -1
- package/dist/chunks/ls-MMA5XS6S.js +8 -0
- package/dist/chunks/{ls-DU5QTKKA.js → ls-QXEB3MBD.js} +1 -1
- package/dist/chunks/ls-UAQ2QDGG.js +8 -0
- package/dist/chunks/{ls-P6LKMT33.js → ls-YA4OQL3F.js} +1 -1
- package/dist/chunks/mutate-AJYMI5UB.js +9 -0
- package/dist/chunks/notifications-DKZMDRHS.js +7 -0
- package/dist/chunks/open-L5DJKOV4.js +7 -0
- package/dist/chunks/openapi-7JUPKBWV.js +7 -0
- package/dist/chunks/{permissions-AE5JO26V.js → permissions-BRSVLT6O.js} +1 -1
- package/dist/chunks/prompt-missing-credentials-PPUSNDNC.js +7 -0
- package/dist/chunks/publish-PXKC5GXE.js +15 -0
- package/dist/chunks/pull-ZBELCNJJ.js +7 -0
- package/dist/chunks/purchase-domain-if-available-BI7AHJMX.js +7 -0
- package/dist/chunks/push-G4JYPC5S.js +7 -0
- package/dist/chunks/{query-PHAGR43V.js → query-JGUDFRPJ.js} +1 -1
- package/dist/chunks/{reauthenticate-O6C2AW3J.js → reauthenticate-DIFJZWC5.js} +1 -1
- package/dist/chunks/reorder-VTFBS2DW.js +10 -0
- package/dist/chunks/reply-HXGAMNR6.js +9 -0
- package/dist/chunks/resolve-IGQSKGRI.js +12 -0
- package/dist/chunks/restore-XKLJMOKB.js +16 -0
- package/dist/chunks/rm-3REOGKTJ.js +8 -0
- package/dist/chunks/rm-C2OYOAJY.js +8 -0
- package/dist/chunks/rm-DL7NRDLF.js +8 -0
- package/dist/chunks/rm-DTF2JN5L.js +8 -0
- package/dist/chunks/rm-SQM4TQOV.js +8 -0
- package/dist/chunks/routes-IPGKJ2E4.js +1 -1
- package/dist/chunks/rule-inspect-PQUJOWHR.js +8 -0
- package/dist/chunks/{rules-6TZ6GSKT.js → rules-IX7WN6XW.js} +1 -1
- package/dist/chunks/schema-R2J4TS6Q.js +14 -0
- package/dist/chunks/{schema-5CZLK6NI.js → schema-WFKR7ULE.js} +1 -1
- package/dist/chunks/{select-org-F2A5JJFH.js → select-org-6AA7XX6E.js} +1 -1
- package/dist/chunks/set-763MJP2G.js +7 -0
- package/dist/chunks/setup-and-link-57NI3GOM.js +7 -0
- package/dist/chunks/{tags-C3HWJLJ4.js → tags-FE4GVQQO.js} +1 -1
- package/dist/chunks/{types-H3B56MH6.js → types-UYIFBCCL.js} +1 -1
- package/dist/chunks/{update-5HE4X45O.js → update-27EMACWZ.js} +1 -1
- package/dist/chunks/vlt-builder-importer-QEWS6M2P.js +11 -0
- package/dist/commands/build/index.js +1 -1
- package/dist/commands/deploy/index.js +5 -5
- package/dist/commands/dev/index.js +23 -20
- package/dist/commands/env/index.js +1 -1
- package/dist/commands/link/index.js +1 -1
- package/dist/commands/list/index.js +2 -2
- package/dist/commands-bulk.js +191 -157
- package/dist/help.js +1 -1
- package/dist/index.js +5 -5
- package/dist/internal-build-worker.js +10 -0
- package/dist/vc.js +46 -4
- package/dist/version.mjs +1 -1
- package/package.json +64 -63
- package/dist/chunks/add-JVSHQKWC.js +0 -8
- package/dist/chunks/add-UKFIETLE.js +0 -8
- package/dist/chunks/add-Z3CJT63N.js +0 -8
- package/dist/chunks/build-SMQYQX23.js +0 -7
- package/dist/chunks/chunk-32QBGZ2Z.js +0 -7
- package/dist/chunks/chunk-3QHJYVCY.js +0 -7
- package/dist/chunks/chunk-5YA32S6K.js +0 -7
- package/dist/chunks/chunk-6C7LA5RA.js +0 -9
- package/dist/chunks/chunk-6PFC3KWQ.js +0 -7
- package/dist/chunks/chunk-ABSRS5KC.js +0 -9
- package/dist/chunks/chunk-AZ6NRDHG.js +0 -7
- package/dist/chunks/chunk-BX5KDMLT.js +0 -10
- package/dist/chunks/chunk-DL665Q3Z.js +0 -7
- package/dist/chunks/chunk-FB5TMOLQ.js +0 -7
- package/dist/chunks/chunk-GRDPI246.js +0 -29
- package/dist/chunks/chunk-J3U3L45Y.js +0 -7
- package/dist/chunks/chunk-KUVMCIR4.js +0 -7
- package/dist/chunks/chunk-LKI6FRNM.js +0 -19
- package/dist/chunks/chunk-M5AV545M.js +0 -7
- package/dist/chunks/chunk-OAKO6LVS.js +0 -7
- package/dist/chunks/chunk-TBBU37TD.js +0 -9
- package/dist/chunks/chunk-TOGR3HUB.js +0 -8
- package/dist/chunks/chunk-WHYH7DVI.js +0 -20
- package/dist/chunks/chunk-X4X5RB2V.js +0 -7
- package/dist/chunks/clear-6IXTTZO6.js +0 -8
- package/dist/chunks/compile-vercel-config-ZFMPTU47.js +0 -7
- package/dist/chunks/config-HLVJQKP7.js +0 -7
- package/dist/chunks/config-XXHMPW46.js +0 -8
- package/dist/chunks/delete-52QKO73X.js +0 -10
- package/dist/chunks/delete-6VOUZDIR.js +0 -9
- package/dist/chunks/detect-services-YYT3LUUX.js +0 -7
- package/dist/chunks/disable-7FGR2S56.js +0 -7
- package/dist/chunks/discard-XKPTY3DC.js +0 -14
- package/dist/chunks/edit-A3HJCNPW.js +0 -8
- package/dist/chunks/edit-A7WGTO6K.js +0 -9
- package/dist/chunks/enable-NGKLGHJ2.js +0 -7
- package/dist/chunks/future-BB7OE645.js +0 -7
- package/dist/chunks/generate-cert-for-deploy-U7JF3HF3.js +0 -7
- package/dist/chunks/import-builders-IFZM44NL.js +0 -7
- package/dist/chunks/inspect-PHUMEO4A.js +0 -9
- package/dist/chunks/inspect-Q7OVSWFO.js +0 -13
- package/dist/chunks/list-G4JM2TYX.js +0 -11
- package/dist/chunks/login-AVVJFLSC.js +0 -9
- package/dist/chunks/login-RMAISH4F.js +0 -7
- package/dist/chunks/logs-3LTU2N25.js +0 -7
- package/dist/chunks/ls-4M2OBNG6.js +0 -8
- package/dist/chunks/ls-HWUYP3XY.js +0 -8
- package/dist/chunks/ls-Y4QR3I6O.js +0 -11
- package/dist/chunks/mutate-KOAALPIL.js +0 -9
- package/dist/chunks/notifications-3RDFNJSD.js +0 -7
- package/dist/chunks/open-VD4F6MAO.js +0 -7
- package/dist/chunks/openapi-DKMCRF2V.js +0 -7
- package/dist/chunks/prompt-missing-credentials-QY4MZDT6.js +0 -7
- package/dist/chunks/publish-YXVJXBQT.js +0 -15
- package/dist/chunks/pull-QLC2CV4J.js +0 -7
- package/dist/chunks/purchase-domain-if-available-74ZYVVBE.js +0 -7
- package/dist/chunks/push-TMPPU5NU.js +0 -7
- package/dist/chunks/reorder-OAJ3NXQQ.js +0 -10
- package/dist/chunks/reply-Q3JFRFA3.js +0 -9
- package/dist/chunks/resolve-XXJVOXNE.js +0 -12
- package/dist/chunks/restore-MO4B2EQV.js +0 -16
- package/dist/chunks/rm-63LFH6NA.js +0 -8
- package/dist/chunks/rm-F2XD2XKB.js +0 -8
- package/dist/chunks/rm-GMG2DZOV.js +0 -8
- package/dist/chunks/rm-P6KA5RSP.js +0 -8
- package/dist/chunks/rm-SZ4HWA4R.js +0 -8
- package/dist/chunks/rule-inspect-JKAXOBII.js +0 -8
- package/dist/chunks/schema-S2ZAREKF.js +0 -14
- package/dist/chunks/set-PIKLGKT6.js +0 -7
- package/dist/chunks/setup-and-link-O5QSQ5K2.js +0 -7
- package/dist/chunks/vlt-builder-importer-YVCYYRVV.js +0 -11
|
@@ -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_dist,require_dist2}from"./chunk-OCWSKPV4.js";import{require_types}from"./chunk-GHM7V3GG.js";import{require_build_utils}from"./chunk-EWWFNMPZ.js";import{__commonJS,__toESM}from"./chunk-6L236MNA.js";var require_dist3=__commonJS({"../../internals/service-topology/dist/index.js"(exports,module){"use strict";var __defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__hasOwnProp=Object.prototype.hasOwnProperty,__export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&typeof from=="object"||typeof from=="function")for(let key of __getOwnPropNames(from))!__hasOwnProp.call(to,key)&&key!==except&&__defProp(to,key,{get:()=>from[key],enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable});return to},__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),src_exports={};__export(src_exports,{INTERNAL_SERVICE_PREFIX:()=>import_fs_detectors2.INTERNAL_SERVICE_PREFIX,autoDetectServices:()=>import_fs_detectors2.autoDetectServices,detectServices:()=>import_fs_detectors2.detectServices,generateServiceRewrites:()=>import_fs_detectors2.generateServiceRewrites,generateServicesRoutes:()=>import_fs_detectors2.generateServicesRoutes,getInternalServiceCronPath:()=>import_fs_detectors2.getInternalServiceCronPath,getInternalServiceCronPathPrefix:()=>import_fs_detectors2.getInternalServiceCronPathPrefix,getInternalServiceFunctionPath:()=>import_fs_detectors2.getInternalServiceFunctionPath,getInternalServiceWorkerPath:()=>import_fs_detectors2.getInternalServiceWorkerPath,getInternalServiceWorkerPathPrefix:()=>import_fs_detectors2.getInternalServiceWorkerPathPrefix,hasLegacyServicesConfig:()=>import_fs_detectors2.hasLegacyServicesConfig,isExperimentalService:()=>import_fs_detectors2.isExperimentalService,isExperimentalServiceV2:()=>import_fs_detectors2.isExperimentalServiceV2,isRouteOwningBuilder:()=>import_fs_detectors2.isRouteOwningBuilder,isStaticBuild:()=>import_fs_detectors2.isStaticBuild,migrateExperimentalServices:()=>import_fs_detectors2.migrateExperimentalServices,planExperimentalServicesMigration:()=>import_fs_detectors2.planExperimentalServicesMigration,resolveAllConfiguredServices:()=>import_fs_detectors2.resolveAllConfiguredServices,resolveAllConfiguredServicesV2:()=>import_fs_detectors2.resolveAllConfiguredServicesV2,resolveConfiguredServiceV2:()=>import_fs_detectors2.resolveConfiguredServiceV2,validateServiceConfigV2:()=>import_fs_detectors2.validateServiceConfigV2});module.exports=__toCommonJS(src_exports);var import_fs_detectors2=require_dist2()}});var import_routing_utils=__toESM(require_dist(),1),import_build_utils=__toESM(require_build_utils(),1),import_types=__toESM(require_types(),1),import_fs_detectors=__toESM(require_dist2(),1);import{getConfigValidator}from"./config-validator.mjs";var imagesSchema={type:"object",additionalProperties:!1,required:["sizes"],properties:{contentDispositionType:{enum:["inline","attachment"]},contentSecurityPolicy:{type:"string",minLength:1,maxLength:256},dangerouslyAllowSVG:{type:"boolean"},domains:{type:"array",minItems:0,maxItems:50,items:{type:"string",minLength:1,maxLength:256}},formats:{type:"array",minItems:1,maxItems:4,items:{enum:["image/avif","image/webp","image/jpeg","image/png"]}},localPatterns:{type:"array",minItems:0,maxItems:25,items:{type:"object",additionalProperties:!1,properties:{pathname:{type:"string",minLength:1,maxLength:256},search:{type:"string",minLength:0,maxLength:256}}}},minimumCacheTTL:{type:"integer",minimum:1,maximum:31536e4},qualities:{type:"array",minItems:1,maxItems:20,items:{type:"integer",minimum:1,maximum:100}},remotePatterns:{type:"array",minItems:0,maxItems:50,items:{type:"object",additionalProperties:!1,required:["hostname"],properties:{protocol:{enum:["http","https"]},hostname:{type:"string",minLength:1,maxLength:256},port:{type:"string",minLength:0,maxLength:5},pathname:{type:"string",minLength:1,maxLength:256},search:{type:"string",minLength:0,maxLength:256}}}},sizes:{type:"array",minItems:1,maxItems:50,items:{type:"number"}}}},cronsSchema={type:"array",minItems:0,items:{type:"object",additionalProperties:!1,required:["path","schedule"],properties:{path:{type:"string",minLength:1,maxLength:512,pattern:"^/.*"},schedule:{type:"string",minLength:9,maxLength:256}}}},schedulesSchema={type:"array",minItems:0,maxItems:100,items:{type:"object",additionalProperties:!1,required:["expression","target","name"],properties:{expression:{type:"object",additionalProperties:!1,required:["cron"],properties:{cron:{type:"string"},jitter:{type:"integer",minimum:1,maximum:15}}},target:{oneOf:[{type:"object",additionalProperties:!1,required:["function"],properties:{function:{type:"string",minLength:1}}},{type:"object",additionalProperties:!1,required:["path"],properties:{path:{description:"Deployment path to invoke over HTTP, like `crons[].path`. Must start with `/`.",type:"string",maxLength:512,pattern:"^/"}}},{type:"object",additionalProperties:!1,required:["topic"],properties:{topic:{type:"string",minLength:1,maxLength:256}}},{type:"object",additionalProperties:!1,required:["entrypoint"],properties:{entrypoint:{type:"string",minLength:1,maxLength:512}}}]},name:{type:"string",minLength:1,maxLength:256},timezone:{type:"string",minLength:1,maxLength:50,description:"IANA timezone for cron evaluation. Defaults to UTC."}}}},experimentalServicesMountSchema={oneOf:[{type:"string",minLength:1,maxLength:512},{type:"object",additionalProperties:!1,properties:{path:{type:"string",minLength:1,maxLength:512},subdomain:{type:"string",minLength:1,maxLength:63}},anyOf:[{required:["path"]},{required:["subdomain"]}]}]},staticExperimentalServiceScheduleSchema={type:"string",minLength:9,maxLength:256,not:{const:"<dynamic>"}},experimentalServiceScheduleSchema={oneOf:[{type:"string",minLength:9,maxLength:256},{type:"array",minItems:1,items:staticExperimentalServiceScheduleSchema}]},experimentalServiceQueueTopicSchema={type:"object",additionalProperties:!1,required:["topic"],properties:{topic:{type:"string",minLength:1,maxLength:256},retryAfterSeconds:{type:"integer",minimum:1,maximum:86400},initialDelaySeconds:{type:"integer",minimum:0,maximum:86400}}},experimentalServiceTopicsSchema={oneOf:[{type:"array",minItems:1,items:{type:"string",minLength:1,maxLength:256}},{type:"array",minItems:1,items:experimentalServiceQueueTopicSchema}]},envVarNamesSchema={pattern:"^[A-Za-z_][A-Za-z0-9_]*$",maxLength:256},getExperimentalServicesCommonProperties=()=>({entrypoint:{type:"string",minLength:1,maxLength:512},root:{type:"string",minLength:1,maxLength:512},workspace:{type:"string",minLength:1,maxLength:512},framework:{type:"string",minLength:1,maxLength:256},builder:{type:"string",minLength:1,maxLength:256},runtime:{type:"string",minLength:1,maxLength:256},buildCommand:{type:"string",minLength:1,maxLength:2048},installCommand:{type:"string",minLength:1,maxLength:2048},preDeployCommand:{type:"string",minLength:1,maxLength:2048},command:{oneOf:[{type:"string",minLength:1,maxLength:2048},{type:"array",minItems:1,items:{type:"string",minLength:1,maxLength:2048}}]},memory:{type:"integer",minimum:128,maximum:10240},maxDuration:(0,import_build_utils.getMaxDurationSchema)(),includeFiles:{oneOf:[{type:"string",minLength:1},{type:"array",items:{type:"string",minLength:1}}]},excludeFiles:{oneOf:[{type:"string",minLength:1},{type:"array",items:{type:"string",minLength:1}}]}}),experimentalServicesRoutableProperties={mount:experimentalServicesMountSchema,routePrefix:{type:"string",minLength:1,maxLength:512},subdomain:{type:"string",minLength:1,maxLength:63}},getExperimentalServicesServiceConfigSchema=()=>({oneOf:[{type:"object",additionalProperties:!1,properties:{...getExperimentalServicesCommonProperties(),...experimentalServicesRoutableProperties,type:{enum:["web"]}}},{type:"object",additionalProperties:!1,required:["type","trigger","schedule"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"job"},trigger:{const:"schedule"},schedule:experimentalServiceScheduleSchema}},{type:"object",additionalProperties:!1,required:["type","trigger","topics"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"job"},trigger:{const:"queue"},topics:experimentalServiceTopicsSchema,consumer:{type:"string",minLength:1,maxLength:256}}},{type:"object",additionalProperties:!1,required:["type","trigger","entrypoint"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"job"},trigger:{const:"workflow"}}},{type:"object",additionalProperties:!1,required:["type"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"worker"},topics:{type:"array",items:{type:"string",minLength:1,maxLength:256},minItems:1},consumer:{type:"string",minLength:1,maxLength:256}}},{type:"object",additionalProperties:!1,required:["type","schedule"],properties:{...getExperimentalServicesCommonProperties(),type:{const:"cron"},schedule:experimentalServiceScheduleSchema}}]}),getExperimentalServicesSchema=()=>({type:"object",propertyNames:{pattern:"^[a-zA-Z]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$",maxLength:64},additionalProperties:getExperimentalServicesServiceConfigSchema()}),experimentalServiceGroupsSchema={type:"object",propertyNames:{pattern:"^[a-zA-Z]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$",maxLength:64},additionalProperties:{type:"array",items:{type:"string",minLength:1,maxLength:256}}},servicesPathSchema={type:"string",minLength:1,maxLength:512},servicesCommandSchema={type:"string",minLength:1,maxLength:2048},servicesServiceNamePattern="^[a-z]([a-z_-]*[a-z])?$",servicesBindingSchema={type:"object",additionalProperties:!1,required:["service","format","env"],properties:{type:{description:"Optional binding type marker. Currently the only supported type is `service`. When present this must be `service`.",const:"service"},service:{type:"string",minLength:1,maxLength:64,pattern:servicesServiceNamePattern},format:{const:"url"},env:{type:"string",...envVarNamesSchema}}},servicesBindingsSchema={type:"array",maxItems:100,items:servicesBindingSchema},getServicesServiceConfigSchema=()=>({type:"object",additionalProperties:!1,required:["root"],properties:{root:servicesPathSchema,framework:{type:"string",minLength:1,maxLength:256},runtime:{type:"string",minLength:1,maxLength:256},entrypoint:servicesPathSchema,command:{oneOf:[{type:"string"},{type:"array",items:{type:"string"}}]},installCommand:servicesCommandSchema,buildCommand:servicesCommandSchema,devCommand:servicesCommandSchema,ignoreCommand:servicesCommandSchema,outputDirectory:servicesPathSchema,bindings:servicesBindingsSchema,functions:(0,import_build_utils.getFunctionsSchema)(),headers:import_routing_utils.headersSchema,redirects:import_routing_utils.redirectsSchema,rewrites:import_routing_utils.rewritesSchema,routes:import_routing_utils.routesSchema,cleanUrls:import_routing_utils.cleanUrlsSchema,trailingSlash:import_routing_utils.trailingSlashSchema}}),getServicesSchema=()=>({type:"object",propertyNames:{pattern:servicesServiceNamePattern,maxLength:64},additionalProperties:getServicesServiceConfigSchema()}),proxySchema={type:"object",additionalProperties:!1,required:["entrypoint"],properties:{entrypoint:{type:"string",minLength:1},matcher:{oneOf:[{type:"string",minLength:1},{type:"array",minItems:1,items:{type:"string",minLength:1}}]}}};function buildVercelConfigSchema(){return{type:"object",additionalProperties:!0,properties:{builds:import_build_utils.buildsSchema,routes:import_routing_utils.routesSchema,cleanUrls:import_routing_utils.cleanUrlsSchema,headers:import_routing_utils.headersSchema,redirects:import_routing_utils.redirectsSchema,rewrites:import_routing_utils.rewritesSchema,trailingSlash:import_routing_utils.trailingSlashSchema,functions:(0,import_build_utils.getFunctionsSchema)(),images:imagesSchema,crons:cronsSchema,schedules:schedulesSchema,bunVersion:{type:"string"},proxy:proxySchema,experimentalServices:getExperimentalServicesSchema(),experimentalServiceGroups:experimentalServiceGroupsSchema,services:getServicesSchema(),experimentalServicesV2:getServicesSchema()}}}function validateConfig(config){let validate=getConfigValidator(buildVercelConfigSchema);if(!validate(config)&&validate.errors&&validate.errors[0]){let error=validate.errors[0],fileName=config[import_types.fileNameSymbol]||"vercel.json",niceError=(0,import_build_utils.getPrettyError)(error);return niceError.message=`Invalid ${fileName} - ${niceError.message}`,niceError}for(let[index,schedule]of(config.schedules??[]).entries())if(schedule.timezone!==void 0)try{if(!/^[A-Za-z][A-Za-z0-9_+/-]*$/.test(schedule.timezone))throw new RangeError("Expected a named timezone");new Intl.DateTimeFormat("en-US",{timeZone:schedule.timezone})}catch{return new import_build_utils.NowBuildError({code:"INVALID_SCHEDULE_TIMEZONE",message:`Invalid ${config[import_types.fileNameSymbol]||"vercel.json"} - \`schedules[${index}].timezone\` must be a valid IANA timezone, such as "America/New_York". Omit it to use UTC.`})}for(let[pattern,fn]of Object.entries(config.functions??{}))if(fn.affinity!==void 0)return new import_build_utils.NowBuildError({code:"FUNCTION_AFFINITY_REQUIRES_SERVICE",message:`Function affinity can only be configured under a service. Move functions[${JSON.stringify(pattern)}].affinity into the relevant service's functions configuration.`,link:"https://vercel.com/docs/concepts/projects/project-configuration#functions"});let functionMaps=[config.functions,...Object.values(config.services??{}).map(service=>service.functions),...Object.values(config.experimentalServicesV2??{}).map(service=>service.functions)];for(let functions of functionMaps)for(let[pattern,fn]of Object.entries(functions??{})){let regions=[...new Set(fn.regions)];if(fn.affinity?.mode==="strict"&&(regions.includes("all")||regions.length>1))return new import_build_utils.NowBuildError({code:"INVALID_FUNCTION_AFFINITY_REGIONS",message:`Function affinity mode "strict" requires at most one statically configured region. Update \`functions[${JSON.stringify(pattern)}].regions\` to contain a single region.`,link:"https://vercel.com/docs/concepts/projects/project-configuration#functions"})}if(config.proxy){let proxyError=(0,import_fs_detectors.validateProxyConfig)(config.proxy);if(proxyError)return new import_build_utils.NowBuildError({code:proxyError.code.toUpperCase(),message:proxyError.message})}if(config.functions&&config.builds)return new import_build_utils.NowBuildError({code:"FUNCTIONS_AND_BUILDS",message:"The `functions` property cannot be used in conjunction with the `builds` property. Please remove one of them.",link:"https://vercel.link/functions-and-builds"});if(config.proxy&&config.builds)return new import_build_utils.NowBuildError({code:"PROXY_AND_BUILDS",message:"The `proxy` property cannot be used with the `builds` property. Remove `builds` to use an explicit proxy entrypoint."});let hasExperimentalServices=!!config.experimentalServices;if(hasExperimentalServices&&config.builds)return new import_build_utils.NowBuildError({code:"EXPERIMENTAL_SERVICES_AND_BUILDS",message:"The `experimentalServices` property cannot be used in conjunction with the `builds` property. Please remove one of them."});if(hasExperimentalServices&&config.functions)return new import_build_utils.NowBuildError({code:"EXPERIMENTAL_SERVICES_AND_FUNCTIONS",message:"The `experimentalServices` property cannot be used in conjunction with the `functions` property. Please remove one of them."});if(config.experimentalServiceGroups&&!config.experimentalServices)return new import_build_utils.NowBuildError({code:"SERVICE_GROUPS_WITHOUT_SERVICES",message:"The `experimentalServiceGroups` property requires `experimentalServices` to be defined. Service groups reference services by name."});let hasServices=config.services!=null,hasExperimentalServicesV2=config.experimentalServicesV2!=null;if(hasServices&&hasExperimentalServicesV2)return new import_build_utils.NowBuildError({code:"SERVICES_AND_EXPERIMENTAL_SERVICES_V2",message:"The `services` property cannot be used in conjunction with its deprecated alias `experimentalServicesV2`. Please use only `services`."});let servicesConfig=config.services??config.experimentalServicesV2,servicesConfigKey=hasServices?"services":"experimentalServicesV2",servicesErrorCodePrefix=hasServices?"SERVICES":"EXPERIMENTAL_SERVICES_V2";if(servicesConfig&&hasExperimentalServices)return new import_build_utils.NowBuildError({code:`${servicesErrorCodePrefix}_AND_EXPERIMENTAL_SERVICES`,message:`The \`${servicesConfigKey}\` property cannot be used in conjunction with the \`experimentalServices\` property. Please use only one services configuration.`});if(servicesConfig&&config.builds)return new import_build_utils.NowBuildError({code:`${servicesErrorCodePrefix}_AND_BUILDS`,message:`The \`${servicesConfigKey}\` property cannot be used in conjunction with the \`builds\` property. Please remove one of them.`});if(servicesConfig){let ambiguousTopLevel=[];if(config.functions!=null&&ambiguousTopLevel.push("functions"),config.installCommand!=null&&ambiguousTopLevel.push("installCommand"),config.buildCommand!=null&&ambiguousTopLevel.push("buildCommand"),config.devCommand!=null&&ambiguousTopLevel.push("devCommand"),config.ignoreCommand!=null&&ambiguousTopLevel.push("ignoreCommand"),config.outputDirectory!=null&&ambiguousTopLevel.push("outputDirectory"),config.framework!=null&&ambiguousTopLevel.push("framework"),ambiguousTopLevel.length>0){let count=ambiguousTopLevel.length,fields=ambiguousTopLevel.map(field=>`\`${field}\``).join(", ");return new import_build_utils.NowBuildError({code:`${servicesErrorCodePrefix}_AND_TOP_LEVEL_BUILD_SETTINGS`,message:`The top-level ${count>1?"properties":"property"} ${fields} cannot be used with \`${servicesConfigKey}\` because the owning service is ambiguous. Move ${count>1?"them":"it"} under the relevant service in \`${servicesConfigKey}\`.`})}}if(servicesConfig){let serviceNames=new Set(Object.keys(servicesConfig));for(let[serviceName,serviceConfig]of Object.entries(servicesConfig))for(let binding of serviceConfig.bindings??[])if(!serviceNames.has(binding.service))return new import_build_utils.NowBuildError({code:`${servicesErrorCodePrefix}_BINDING_UNKNOWN_SERVICE`,message:`Service "${serviceName}" declares a binding to unknown service "${binding.service}". Add "${binding.service}" to \`${servicesConfigKey}\` or fix the binding.`})}return null}export{require_dist3 as require_dist,validateConfig};
|
|
@@ -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{getGlobalPathConfig}from"./chunk-JSKGZLE4.js";import{require_load_json_file}from"./chunk-RCTYVKM5.js";import{require_types}from"./chunk-GHM7V3GG.js";import{inspectTokenRequest,processInspectTokenResponse}from"./chunk-5XJNPXQK.js";import{parseArguments}from"./chunk-WWB66KP5.js";import{DEFAULT_VERCEL_CONFIG_FILENAME,VERCEL_CONFIG_EXTENSIONS,VERCEL_DIR,findProjectsFromPath,getLinkFromDir,getRepoLink,getVercelDirectory}from"./chunk-TTKDYUJD.js";import{humanizePath}from"./chunk-PPCFQQSU.js";import{require_cli_config}from"./chunk-BRK4OB4B.js";import{getUser}from"./chunk-SM5JI6QM.js";import{getTeamByIdOrSlug}from"./chunk-VOZEB6PD.js";import{ConflictingConfigFiles,DeprecatedNowJson,InvalidLocalConfig,InvalidToken,NowError,TeamDeleted}from"./chunk-RINZXCDJ.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{require_dist}from"./chunk-QGIQK47P.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";var import_chalk=__toESM(require_source(),1);function highlight(text){return import_chalk.default.bold.underline(text)}var VERCEL_API_ORIGIN="https://api.vercel.com";async function introspectToken(client){let token=client.authConfig.token;if(!token)throw new Error("No token to introspect");if(new URL(client.apiUrl).origin!==VERCEL_API_ORIGIN)throw new Error("Token introspection is unavailable for custom API origins");let[error,introspection]=await processInspectTokenResponse(await inspectTokenRequest(token));if(error)throw error;return introspection}function isAppPrincipalEnabled(){return!!process.env.APP_PRINCIPAL_ENABLED}function resolveAppFromToken(token){return!token.active||!token.client_id?null:{id:token.client_id,name:token.client_name}}async function resolveAppTokenScope(client,scope){let token=await introspectToken(client).catch(()=>null),app=token?resolveAppFromToken(token):null,team=token?.team;return!app||!team||team.id!==scope&&team.slug!==scope?!1:(client.config.currentTeam=team.id,!0)}import{relative}from"path";var import_cli_config=__toESM(require_cli_config(),1);var import_load_json_file=__toESM(require_load_json_file(),1),config=__toESM(require_cli_config(),1),import_error_utils=__toESM(require_dist(),1),import_types=__toESM(require_types(),1);import{join,basename,dirname}from"path";import{accessSync,constants}from"fs";import{persistCliAuthConfig,readCliAuthConfig}from"@vercel/cli-auth/credentials-store.js";import path from"path";import{existsSync}from"fs";function getLocalPathConfig(prefix,useCompiledConfig=!0){let customPath=parseArguments(process.argv.slice(2),{},{permissive:!0}).flags["--local-config"];if(customPath){if(typeof customPath!="string")throw new InvalidLocalConfig(customPath);return path.resolve(process.cwd(),customPath)}let vercelConfigPath=path.join(prefix,"vercel.json"),vercelTomlPath=path.join(prefix,"vercel.toml"),nowConfigPath=path.join(prefix,"now.json"),vercelConfigExists=existsSync(vercelConfigPath),vercelTomlExists=existsSync(vercelTomlPath),nowConfigExists=existsSync(nowConfigPath),foundConfigs=[];if(vercelConfigExists&&foundConfigs.push(vercelConfigPath),vercelTomlExists&&foundConfigs.push(vercelTomlPath),nowConfigExists)throw new DeprecatedNowJson(nowConfigPath);if(foundConfigs.length>1)throw new ConflictingConfigFiles(foundConfigs);let compiledConfigPath=path.join(prefix,VERCEL_DIR,"vercel.json"),compiledConfigExists=existsSync(compiledConfigPath);return useCompiledConfig&&compiledConfigExists?compiledConfigPath:vercelConfigPath}var VERCEL_DIR2=getGlobalPathConfig(),CONFIG_FILE_PATH=config.getConfigFilePath(VERCEL_DIR2),AUTH_CONFIG_FILE_PATH=config.getAuthConfigFilePath(VERCEL_DIR2),readConfigFile=()=>config.readGlobalConfigFile(CONFIG_FILE_PATH),writeToConfigFile=stuff=>{try{config.writeGlobalConfigFile(CONFIG_FILE_PATH,stuff)}catch(err){throw(0,import_error_utils.isErrnoException)(err)&&((0,import_error_utils.isErrnoException)(err)&&err.code==="EPERM"?(output_manager_default.error(`Not able to create ${highlight(CONFIG_FILE_PATH)} (operation not permitted).`),process.exit(1)):err.code==="EBADF"&&(output_manager_default.error(`Not able to create ${highlight(CONFIG_FILE_PATH)} (bad file descriptor).`),process.exit(1))),err}},readAuthConfigFile=_globalConfig=>({...config.getDefaultAuthConfig(),...readCliAuthConfig(VERCEL_DIR2)}),persistAuthConfig=(authConfig,_globalConfig)=>{try{return persistCliAuthConfig(VERCEL_DIR2,authConfig)}catch(err){let wrappedError=new Error(`Not able to create ${humanizePath(AUTH_CONFIG_FILE_PATH)} (${(0,import_error_utils.errorToStringFriendly)(err)}).`);throw wrappedError.cause=err,wrappedError}};function getConfigFilePath2(){return CONFIG_FILE_PATH}function getAuthConfigFilePath2(){return AUTH_CONFIG_FILE_PATH}function readLocalConfig(prefix=process.cwd()){let config2,target="";try{target=getLocalPathConfig(prefix)}catch(err){if(err instanceof NowError)output_manager_default.error(err.message),process.exit(1);else throw err}if(!target)return;try{accessSync(target,constants.F_OK),config2=import_load_json_file.default.sync(target)}catch(err){if(!((0,import_error_utils.isErrnoException)(err)&&err.code==="ENOENT"))if((0,import_error_utils.isError)(err)&&err.name==="JSONError")output_manager_default.error(err.message),process.exit(1);else if((0,import_error_utils.isErrnoException)(err)){let code=err.code?` (${err.code})`:"";output_manager_default.error(`Failed to read config file: ${target}${code}`),process.exit(1)}else output_manager_default.prettyError(err),process.exit(1)}if(!config2)return;if(basename(target)==="vercel.json"&&basename(dirname(target))===VERCEL_DIR){let workPath=dirname(dirname(target)),sourceFile=null;for(let ext of VERCEL_CONFIG_EXTENSIONS){let configPath=join(workPath,`vercel.${ext}`);try{accessSync(configPath,constants.F_OK),sourceFile=basename(configPath);break}catch{}}if(!sourceFile){let tomlPath=join(workPath,"vercel.toml");try{accessSync(tomlPath,constants.F_OK),sourceFile="vercel.toml"}catch{}}config2[import_types.fileNameSymbol]=sourceFile||DEFAULT_VERCEL_CONFIG_FILENAME}else config2[import_types.fileNameSymbol]=basename(target);return config2}function isEligibleForNativeBinaryAutoOptIn(client){return client.teams?.some(team=>team.slug==="vercel")===!0}function autoOptInNativeBinary(client){let envOverride=process.env.VERCEL_CLI_USE_NATIVE_BINARY;if(!(envOverride==="false"||envOverride==="0"||typeof client.config.useNativeBinary=="boolean"||client.config.nativeBinaryAutoOptIn===!0||!isEligibleForNativeBinaryAutoOptIn(client)))try{let configPath=getConfigFilePath2(),savedConfig=(0,import_cli_config.readGlobalConfigFile)(configPath);if(typeof savedConfig.useNativeBinary=="boolean"||savedConfig.nativeBinaryAutoOptIn===!0)return;let config2={...savedConfig,nativeBinaryAutoOptIn:!0};(0,import_cli_config.writeGlobalConfigFile)(configPath,config2),client.config={...client.config,nativeBinaryAutoOptIn:!0}}catch{output_manager_default.debug("Failed to persist automatic native binary enrollment.")}}async function getScope(client,opts={}){let{user,app,token}=await getPrincipal(client);user&&autoOptInNativeBinary(client);let defaultTeamId=user?.version==="northstar"?user.defaultTeamId:void 0,appTeamId=!user&&app?token?.team?.id:void 0;if(!user&&app&&opts.getTeam===!1)throw new Error("App principal scope resolution requires a team lookup.");!user&&app&&(client.config.currentTeam=appTeamId),!client.config.currentTeam&&defaultTeamId&&(client.config.currentTeam=defaultTeamId);let teamId=client.config.currentTeam||defaultTeamId,team=teamId&&opts.getTeam!==!1?await getTeam(client,teamId):null,contextName=team?.slug||user?.username||user?.email;if(!contextName)throw new Error("Unable to determine context name");return opts.resolveLocalScope?resolveLocalScopeContext(client,{user,app,team}):{contextName,team,user,app}}async function getPrincipal(client){if(!isAppPrincipalEnabled())return{user:await getUser(client),app:null,token:null};let[userResult,tokenResult]=await Promise.allSettled([getUser(client),introspectToken(client)]),token=tokenResult.status==="fulfilled"?tokenResult.value:null,app=token?resolveAppFromToken(token):null;if(userResult.status==="rejected"&&!(app&&userResult.reason instanceof InvalidToken))throw userResult.reason;return{user:userResult.status==="fulfilled"?userResult.value:null,app,token}}async function resolveLocalScopeContext(client,{user,app,team}){let explicitScopeProvided=detectExplicitScope(client),globalTeamId=client.config.currentTeam,{localOrgId,linkedRepo,isCrossTeamRepo}=await findLocalLink(client),isAppPrincipal=!user&&!!app,effectiveLocalOrgId=isAppPrincipal?void 0:localOrgId,scopeMismatch=!!(effectiveLocalOrgId&&globalTeamId&&globalTeamId!==effectiveLocalOrgId);!isAppPrincipal&&!explicitScopeProvided&&!effectiveLocalOrgId&&isCrossTeamRepo&&output_manager_default.warn("This repository has projects across multiple teams. Use `--scope` to specify which team, or `cd` into a project directory.");let resolvedTeam=!explicitScopeProvided&&effectiveLocalOrgId?await applyLocalOrg(client,effectiveLocalOrgId):team,{org,contextName}=resolveOrg(resolvedTeam,user);return{org,contextName,user,team:resolvedTeam,app,globalTeam:team,linkedRepo,isCrossTeamRepo,scopeMismatch,explicitScopeProvided}}async function applyLocalOrg(client,localOrgId){return client.config.currentTeam=localOrgId.startsWith("team_")?localOrgId:void 0,client.config.currentTeam?await getTeamByIdOrSlug(client,client.config.currentTeam):null}async function getTeam(client,teamId){let team=await getTeamByIdOrSlug(client,teamId);if(!team)throw new TeamDeleted;return team}function resolveOrg(team,user){if(team)return{org:{type:"team",id:team.id,slug:team.slug},contextName:team.slug};if(user)return{org:{type:"user",id:user.id,slug:user.username},contextName:user.username||user.email};throw new Error("Unable to determine scope: no team or personal account is available for this token. Use `--scope` to specify a team.")}async function findLocalLink(client){let[projectLink,repoLink]=await Promise.all([findProjectLink(client),findRepoLink(client)]);return{localOrgId:findLocalOrgId(client.cwd,projectLink,repoLink),linkedRepo:repoLink?.repoConfig?{repoConfig:repoLink.repoConfig,rootPath:repoLink.rootPath}:null,isCrossTeamRepo:detectCrossTeamRepo(repoLink?.repoConfig)}}async function findProjectLink(client){try{return await getLinkFromDir(getVercelDirectory(client.cwd))}catch{return null}}async function findRepoLink(client){try{return await getRepoLink(client,client.cwd)}catch{return null}}function findLocalOrgId(cwd,projectLink,repoLink){if(projectLink)return projectLink.orgId;if(repoLink?.repoConfig)return findRepoOrgId(repoLink.repoConfig,relative(repoLink.rootPath,cwd))}function findRepoOrgId(repoConfig,pathFromRepoRoot){let projects=findProjectsFromPath(repoConfig.projects,pathFromRepoRoot),orgIds=new Set(projects.map(p=>p.orgId??repoConfig.orgId??""));if(orgIds.size!==1)return;let[orgId]=orgIds;return orgId||void 0}function detectExplicitScope(client){let argv=client.argv;for(let arg of argv){if(arg==="--")break;if(arg==="--scope"||arg==="--team"||arg.startsWith("--scope=")||arg.startsWith("--team=")||arg==="-S"||arg==="-T")return!0}return!!client.localConfig?.scope}function detectCrossTeamRepo(repoConfig){if(!repoConfig?.projects||repoConfig.projects.length<2)return!1;let orgIds=new Set;for(let project of repoConfig.projects){let orgId=project.orgId??repoConfig.orgId;orgId&&orgIds.add(orgId)}return orgIds.size>1}export{highlight,isAppPrincipalEnabled,resolveAppTokenScope,getScope,detectExplicitScope,getLocalPathConfig,readConfigFile,writeToConfigFile,readAuthConfigFile,persistAuthConfig,getConfigFilePath2 as getConfigFilePath,getAuthConfigFilePath2 as getAuthConfigFilePath,readLocalConfig};
|
|
@@ -4,4 +4,4 @@ import { dirname as __dirname_ } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
const __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{outputError,writeJsonError}from"./chunk-FA6O7FPC.js";import{resolveProjectContext}from"./chunk-
|
|
7
|
+
import{outputError,writeJsonError}from"./chunk-FA6O7FPC.js";import{resolveProjectContext}from"./chunk-GL7HB5ZK.js";import{detectExplicitScope,getScope}from"./chunk-LFQTA3CF.js";import{printError}from"./chunk-N5AIKGEO.js";import{getLinkedProject}from"./chunk-TTKDYUJD.js";import{isAPIError}from"./chunk-RINZXCDJ.js";import{getCommandName}from"./chunk-FI772UVH.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";function handleCommentsParseError(err,subcommandName){return printError(err),err instanceof Error&&/unknown or unexpected option: -[^-]/.test(err.message)&&output_manager_default.log(`An argument starting with "-"? Put it after \`--\`: ${getCommandName(`comments ${subcommandName} -- <arg>`)}`),output_manager_default.log(`Run ${getCommandName(`comments ${subcommandName} --help`)} for usage.`),1}function threadNotFoundMessage(threadId,scope){return`Comment not found: ${threadId} in team ${scope.teamSlug??scope.teamId}. If it belongs to another team, pass --scope <team>.`}function query(teamId,params={}){let search=new URLSearchParams({teamId});for(let[key,value]of Object.entries(params))if(value!==void 0)if(Array.isArray(value))for(let entry of value)search.append(key,entry);else search.set(key,String(value));return search.toString()}var fetchOpts={useCurrentTeam:!1};function listThreads(client,teamId,params){return client.fetch(`/toolbar/threads?${query(teamId,{...params})}`,fetchOpts)}function getThread(client,teamId,threadId){return client.fetch(`/toolbar/threads/${encodeURIComponent(threadId)}?${query(teamId)}`,fetchOpts)}function updateThread(client,teamId,threadId,resolved){return client.fetch(`/toolbar/threads/${encodeURIComponent(threadId)}?${query(teamId)}`,{...fetchOpts,method:"PATCH",body:{resolved}})}function listMessages(client,teamId,threadId,opts={}){return client.fetch(`/toolbar/threads/${encodeURIComponent(threadId)}/messages?${query(teamId,{...opts})}`,fetchOpts)}function addMessage(client,teamId,threadId,body){return client.fetch(`/toolbar/threads/${encodeURIComponent(threadId)}/messages?${query(teamId)}`,{...fetchOpts,method:"POST",body})}function updateMessage(client,teamId,threadId,messageId,body){return client.fetch(`/toolbar/threads/${encodeURIComponent(threadId)}/messages/${encodeURIComponent(messageId)}?${query(teamId)}`,{...fetchOpts,method:"PATCH",body})}function deleteMessage(client,teamId,threadId,messageId){return client.fetch(`/toolbar/threads/${encodeURIComponent(threadId)}/messages/${encodeURIComponent(messageId)}?${query(teamId)}`,{...fetchOpts,method:"DELETE"})}function toApiErrorParts(err){let apiErr=err;return{code:apiErr.code||"API_ERROR",message:apiErr.serverMessage||`API error (${apiErr.status??"unknown"}).`}}import{spawnSync}from"node:child_process";async function resolveCommentsScope(client,opts){if(opts.urlTeamSlug&&!opts.project&&!detectExplicitScope(client))return{teamId:opts.urlTeamSlug,teamSlug:opts.urlTeamSlug};if(opts.project){let context;try{context=await resolveProjectContext({client,projectNameOrId:opts.project,projectNotFoundHandling:opts.jsonOutput?"return":"report"})}catch(err){if(isAPIError(err))return outputError(client,opts.jsonOutput,err.code||"API_ERROR",err.serverMessage||`API error (${err.status}).`);throw err}return context.status==="error"?(opts.jsonOutput&&writeJsonError(client,"PROJECT_CONTEXT_ERROR","Could not resolve the project context."),context.exitCode):context.status==="not_linked"?outputError(client,opts.jsonOutput,"PROJECT_NOT_FOUND",`Project "${opts.project}" was not found in the current scope.`):{teamId:context.org.id,teamSlug:context.org.slug,projectId:context.project.id,projectName:context.project.name,linked:!!context.repoRoot}}let linked=await getLinkedProject(client);if(linked.status==="error")return linked.exitCode;if(linked.status==="linked"){if(detectExplicitScope(client)){let{team:team2}=await getScope(client);if(!team2)return outputError(client,opts.jsonOutput,"NO_TEAM","No team context found for --scope.");if(team2.id!==linked.org.id)return opts.requireProject?outputError(client,opts.jsonOutput,"SCOPE_PROJECT_MISMATCH",`--scope ${team2.slug} does not match the linked project's team (${linked.org.slug}). Pass --project <name-or-id> for a project in ${team2.slug}.`):{teamId:team2.id,teamSlug:team2.slug}}return{teamId:linked.org.id,teamSlug:linked.org.slug,projectId:linked.project.id,projectName:linked.project.name,linked:!0}}if(opts.requireProject)return outputError(client,opts.jsonOutput,"NOT_LINKED","No linked project found. Run `vercel link` to link a project, or pass --project <name-or-id>.");let{team}=await getScope(client);return team?{teamId:team.id,teamSlug:team.slug}:outputError(client,opts.jsonOutput,"NO_TEAM","No team context found. Run `vercel switch` to select a team, or run `vercel link` in a project directory.")}function inferBranch(cwd){let result=spawnSync("git",["rev-parse","--abbrev-ref","HEAD"],{cwd,encoding:"utf8"});if(result.status===0){let branch=result.stdout.trim();if(branch&&branch!=="HEAD")return{value:branch,source:"git"}}let ciRef=process.env.VERCEL_GIT_COMMIT_REF||process.env.GITHUB_HEAD_REF||process.env.GITHUB_REF_NAME;if(ciRef)return{value:ciRef,source:"ci"}}export{handleCommentsParseError,threadNotFoundMessage,listThreads,getThread,updateThread,listMessages,addMessage,updateMessage,deleteMessage,toApiErrorParts,resolveCommentsScope,inferBranch};
|
|
@@ -4,9 +4,9 @@ import { dirname as __dirname_ } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
const __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{require_dist as require_dist2}from"./chunk-TRTEXGVN.js";import{sleep}from"./chunk-T3GQAMBJ.js";import{
|
|
8
|
-
`,message=prependEmoji(import_chalk.default.dim(payload),emoji(type))+newline,finalLink="";link&&(finalLink=import_chalk.default.dim(`${action||"Learn More"}: ${link_default(link)}`)+newline),output_manager_default.print(message+finalLink)}}}}function sharedPromise(fn){let promise=null;return function(...args){return promise||(promise=fn.apply(this,args),promise.finally(()=>{promise=null})),promise}}var
|
|
9
|
-
${error.stack}`)};this.setArgv(opts.argv),this.apiUrl=opts.apiUrl,this.authConfig=opts.authConfig,this.stdin=opts.stdin,this.stdout=opts.stdout,this.stderr=opts.stderr,this.config=opts.config,this.localConfig=opts.localConfig,this.localConfigPath=opts.localConfigPath,this.requestIdCounter=1,this.telemetryEventStore=opts.telemetryEventStore,this.isAgent=opts.isAgent??!1,this.agentName=opts.agentName,this.nonInteractive=opts.nonInteractive??this.isAgent,this.dangerouslySkipPermissions=opts.dangerouslySkipPermissions??!1;let theme={prefix:(0,import_chalk2.gray)("?"),style:{answer:import_chalk2.gray}};this.input={text:async opts2=>{let{default:input}=await import("./esm-7HVUFWMN.js");return this.runPrompt(input({theme,...opts2},{input:this.stdin,output:this.stderr}))},password:async opts2=>{let{default:password}=await import("./esm-BZBEM7YA.js");return this.runPrompt(password({theme,...opts2},{input:this.stdin,output:this.stderr}))},checkbox:async opts2=>{let{default:checkbox}=await import("./esm-CXICLFA3.js");return this.runPrompt(checkbox({theme,...opts2},{input:this.stdin,output:this.stderr}))},expand:async opts2=>{let{default:expand}=await import("./esm-HDEHVK7I.js");return this.runPrompt(expand({theme,...opts2},{input:this.stdin,output:this.stderr}))},confirm:async(message,default_value)=>{let{default:confirm}=await import("./esm-SZZI53W7.js");return this.runPrompt(confirm({theme,message,default:default_value},{input:this.stdin,output:this.stderr}))},select:async opts2=>{let{default:select}=await import("./esm-WGJFGCLK.js");return this.runPrompt(select({theme,...opts2},{input:this.stdin,output:this.stderr}))},search:async opts2=>{let{default:search}=await import("./esm-NQRLKALI.js");return this.runPrompt(search({theme,...opts2},{input:this.stdin,output:this.stderr}))}}}async withEscapePromptCancellation(run){this.escapePromptCancellationDepth++;try{return await run()}finally{this.escapePromptCancellationDepth--}}async withPromptBackNavigation(run){this.promptBackNavigationDepth++;try{return await run()}finally{this.promptBackNavigationDepth--}}runPrompt(prompt){let escapeCancellationEnabled=this.escapePromptCancellationDepth>0,backNavigationEnabled=this.promptBackNavigationDepth>0;if(!escapeCancellationEnabled&&!backNavigationEnabled||!this.stdin.isTTY||!prompt.cancel)return prompt;let cancellation,onKeypress=(_input,key)=>{key?.name==="escape"&&escapeCancellationEnabled&&!cancellation?(cancellation="escape",prompt.cancel?.()):key?.name==="up"&&backNavigationEnabled&&!cancellation&&(cancellation="back",prompt.cancel?.())};return this.stdin.on("keypress",onKeypress),prompt.catch(error=>{throw cancellation==="escape"?new PromptCanceledError:cancellation==="back"?new PromptBackError:error}).finally(()=>{this.stdin.off("keypress",onKeypress)})}get argv(){return this._argv}setArgv(argvOrFirst,...rest){let argv=Array.isArray(argvOrFirst)?argvOrFirst:[argvOrFirst,...rest];this._argv=argv,this._parsedArgsCache=void 0}getParsedArgs(){return this._parsedArgsCache||(this._parsedArgsCache=parseArguments(this.argv.slice(2),{},{permissive:!0})),this._parsedArgsCache}retry(fn,{retries=3,maxTimeout=1/0}={}){return(0,import_async_retry.default)(fn,{retries,maxTimeout,onRetry:this._onRetry})}async ensureAuthorized(){let{authConfig}=this;if(isValidAccessToken(authConfig)){this._loggedTokenSource||(authConfig.tokenSource==="flag"?output_manager_default.debug("Using token from `--token` argument, skipping token refresh."):authConfig.tokenSource==="env"?output_manager_default.debug("Using token from VERCEL_TOKEN environment variable, skipping token refresh."):output_manager_default.debug("Valid access token, skipping token refresh."),this._loggedTokenSource=!0);return}if(!hasRefreshToken(authConfig)){output_manager_default.debug("No refresh token found, emptying auth config."),this.emptyAuthConfig(),this.persistAuthConfig();return}let tokenResponse=await refreshTokenRequest({refresh_token:authConfig.refreshToken}),[tokensError,tokens]=await processTokenResponse(tokenResponse);if(isOAuthError(tokensError)&&tokensError.code==="invalid_grant"&&!authConfig.tokenSource&&this.stdin.isTTY&&!this.nonInteractive){output_manager_default.debug(`Stored session refresh failed: ${tokensError.cause.message}`),output_manager_default.log("Couldn't refresh the saved login. Starting a new login.");let{performDeviceCodeFlow}=await import("./future-
|
|
7
|
+
import{require_dist as require_dist2}from"./chunk-TRTEXGVN.js";import{sleep}from"./chunk-T3GQAMBJ.js";import{PromptBackError,PromptCanceledError}from"./chunk-P2O5DOYE.js";import{persistAuthConfig,writeToConfigFile}from"./chunk-LFQTA3CF.js";import{isOAuthError,processTokenResponse,refreshTokenRequest,ua_default}from"./chunk-5XJNPXQK.js";import{parseArguments}from"./chunk-WWB66KP5.js";import{fetch}from"./chunk-MY4MONOH.js";import{require_cli_config}from"./chunk-BRK4OB4B.js";import{APIError}from"./chunk-RINZXCDJ.js";import{emoji,link_default,output_manager_default,prependEmoji}from"./chunk-EWWFNMPZ.js";import{require_dist}from"./chunk-QGIQK47P.js";import{pkg_default}from"./chunk-AVSPFBLM.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";var import_chalk2=__toESM(require_source(),1),import_cli_config=__toESM(require_cli_config(),1),import_async_retry=__toESM(require_dist2(),1);import{join,resolve}from"node:path";import{EventEmitter}from"events";import{URL}from"url";async function responseError(res,fallbackMessage=null,parsedBody={}){let bodyError;if(!res.ok){let body;try{body=await res.json()}catch{body=parsedBody}bodyError=body.error||body.err||body}let msg=bodyError?.message||fallbackMessage||"Response Error";return new APIError(msg,res,bodyError)}var import_chalk=__toESM(require_source(),1);function printIndications(res){let indications=new Set(["warning","notice","tip"]),regex=/^x-(?:vercel|now)-(warning|notice|tip)-(.*)$/;for(let[name,payload]of res.headers){let match=name.match(regex);if(match){let[,type,identifier]=match,action=res.headers.get(`x-vercel-action-${identifier}`),link=res.headers.get(`x-vercel-link-${identifier}`);if(indications.has(type)){let newline=`
|
|
8
|
+
`,message=prependEmoji(import_chalk.default.dim(payload),emoji(type))+newline,finalLink="";link&&(finalLink=import_chalk.default.dim(`${action||"Learn More"}: ${link_default(link)}`)+newline),output_manager_default.print(message+finalLink)}}}}function sharedPromise(fn){let promise=null;return function(...args){return promise||(promise=fn.apply(this,args),promise.finally(()=>{promise=null})),promise}}var import_error_utils=__toESM(require_dist(),1);var DOMAINS_API_PATH=/^\/v\d+\/(?:domains|registrar)(?:\/|$)/,isSAMLError=v=>v&&v.saml,isJSONObject=v=>v&&typeof v=="object"&&v.constructor===Object;function isValidAccessToken(authConfig){if(!authConfig.token)return!1;if(typeof authConfig.expiresAt!="number")return!0;let nowInSeconds=Math.floor(Date.now()/1e3);return authConfig.expiresAt>=nowInSeconds}function hasRefreshToken(authConfig){return"refreshToken"in authConfig}var Client=class extends EventEmitter{constructor(opts){super();this._argv=[];this._loggedTokenSource=!1;this.escapePromptCancellationDepth=0;this.promptBackNavigationDepth=0;this.reauthenticate=sharedPromise(async function(error){let{default:reauthenticate}=await import("./reauthenticate-DIFJZWC5.js");if(typeof await reauthenticate(this,error)=="number")throw error instanceof APIError?output_manager_default.prettyError(error):output_manager_default.error(`Failed to re-authenticate for ${(0,import_chalk2.bold)(error.scope)} scope`),error});this._onRetry=error=>{output_manager_default.debug(`Retrying: ${error}
|
|
9
|
+
${error.stack}`)};this.setArgv(opts.argv),this.apiUrl=opts.apiUrl,this.authConfig=opts.authConfig,this.stdin=opts.stdin,this.stdout=opts.stdout,this.stderr=opts.stderr,this.config=opts.config,this.localConfig=opts.localConfig,this.localConfigPath=opts.localConfigPath,this.requestIdCounter=1,this.telemetryEventStore=opts.telemetryEventStore,this.isAgent=opts.isAgent??!1,this.agentName=opts.agentName,this.nonInteractive=opts.nonInteractive??this.isAgent,this.dangerouslySkipPermissions=opts.dangerouslySkipPermissions??!1;let theme={prefix:(0,import_chalk2.gray)("?"),style:{answer:import_chalk2.gray}};this.input={text:async opts2=>{let{default:input}=await import("./esm-7HVUFWMN.js");return this.runPrompt(input({theme,...opts2},{input:this.stdin,output:this.stderr}))},password:async opts2=>{let{default:password}=await import("./esm-BZBEM7YA.js");return this.runPrompt(password({theme,...opts2},{input:this.stdin,output:this.stderr}))},checkbox:async opts2=>{let{default:checkbox}=await import("./esm-CXICLFA3.js");return this.runPrompt(checkbox({theme,...opts2},{input:this.stdin,output:this.stderr}))},expand:async opts2=>{let{default:expand}=await import("./esm-HDEHVK7I.js");return this.runPrompt(expand({theme,...opts2},{input:this.stdin,output:this.stderr}))},confirm:async(message,default_value)=>{let{default:confirm}=await import("./esm-SZZI53W7.js");return this.runPrompt(confirm({theme,message,default:default_value},{input:this.stdin,output:this.stderr}))},select:async opts2=>{let{default:select}=await import("./esm-WGJFGCLK.js");return this.runPrompt(select({theme,...opts2},{input:this.stdin,output:this.stderr}))},search:async opts2=>{let{default:search}=await import("./esm-NQRLKALI.js");return this.runPrompt(search({theme,...opts2},{input:this.stdin,output:this.stderr}))}}}async withEscapePromptCancellation(run){this.escapePromptCancellationDepth++;try{return await run()}finally{this.escapePromptCancellationDepth--}}async withPromptBackNavigation(run){this.promptBackNavigationDepth++;try{return await run()}finally{this.promptBackNavigationDepth--}}runPrompt(prompt){let escapeCancellationEnabled=this.escapePromptCancellationDepth>0,backNavigationEnabled=this.promptBackNavigationDepth>0;if(!escapeCancellationEnabled&&!backNavigationEnabled||!this.stdin.isTTY||!prompt.cancel)return prompt;let cancellation,onKeypress=(_input,key)=>{key?.name==="escape"&&escapeCancellationEnabled&&!cancellation?(cancellation="escape",prompt.cancel?.()):key?.name==="up"&&backNavigationEnabled&&!cancellation&&(cancellation="back",prompt.cancel?.())};return this.stdin.on("keypress",onKeypress),prompt.catch(error=>{throw cancellation==="escape"?new PromptCanceledError:cancellation==="back"?new PromptBackError:error}).finally(()=>{this.stdin.off("keypress",onKeypress)})}get argv(){return this._argv}setArgv(argvOrFirst,...rest){let argv=Array.isArray(argvOrFirst)?argvOrFirst:[argvOrFirst,...rest];this._argv=argv,this._parsedArgsCache=void 0}getParsedArgs(){return this._parsedArgsCache||(this._parsedArgsCache=parseArguments(this.argv.slice(2),{},{permissive:!0})),this._parsedArgsCache}retry(fn,{retries=3,maxTimeout=1/0}={}){return(0,import_async_retry.default)(fn,{retries,maxTimeout,onRetry:this._onRetry})}async ensureAuthorized(){let{authConfig}=this;if(isValidAccessToken(authConfig)){this._loggedTokenSource||(authConfig.tokenSource==="flag"?output_manager_default.debug("Using token from `--token` argument, skipping token refresh."):authConfig.tokenSource==="env"?output_manager_default.debug("Using token from VERCEL_TOKEN environment variable, skipping token refresh."):output_manager_default.debug("Valid access token, skipping token refresh."),this._loggedTokenSource=!0);return}if(!hasRefreshToken(authConfig)){output_manager_default.debug("No refresh token found, emptying auth config."),this.emptyAuthConfig(),this.persistAuthConfig();return}let tokenResponse=await refreshTokenRequest({refresh_token:authConfig.refreshToken}),[tokensError,tokens]=await processTokenResponse(tokenResponse);if(isOAuthError(tokensError)&&tokensError.code==="invalid_grant"&&!authConfig.tokenSource&&this.stdin.isTTY&&!this.nonInteractive){output_manager_default.debug(`Stored session refresh failed: ${tokensError.cause.message}`),output_manager_default.log("Couldn't refresh the saved login. Starting a new login.");let{performDeviceCodeFlow}=await import("./future-IGDV62BF.js"),recoveredTokens=await performDeviceCodeFlow(this);if(recoveredTokens){this.updateAuthConfig({token:recoveredTokens.access_token,userId:void 0,expiresAt:Math.floor(Date.now()/1e3)+recoveredTokens.expires_in,refreshToken:recoveredTokens.refresh_token}),this.persistAuthConfig();return}}if(tokensError){output_manager_default.debug("Error refreshing token, emptying auth config."),this.emptyAuthConfig(),this.persistAuthConfig();return}this.updateAuthConfig({token:tokens.access_token,expiresAt:Math.floor(Date.now()/1e3)+tokens.expires_in}),tokens.refresh_token&&this.updateAuthConfig({refreshToken:tokens.refresh_token}),this.persistAuthConfig(),this.writeToConfigFile(),output_manager_default.debug("Tokens refreshed successfully.")}getGlobalPathConfig(){let confFlag=this.getParsedArgs().flags["--global-config"];return typeof confFlag=="string"?resolve(this.cwd,confFlag):(0,import_cli_config.getGlobalPathConfig)()}async readConfig(fileName,schema){let filePath=join(this.getGlobalPathConfig(),fileName);return(0,import_cli_config.readConfigFile)(filePath,schema)}async maybeReadConfig(fileName,schema){try{return await this.readConfig(fileName,schema)}catch{return null}}async writeConfig(fileName,schema,value){let filePath=join(this.getGlobalPathConfig(),fileName);(0,import_cli_config.writeConfigFile)(filePath,schema,value)}updateConfig(config){this.config={...this.config,...config}}writeToConfigFile(){writeToConfigFile(this.config)}updateAuthConfig(authConfig){authConfig.token&&authConfig.token!==this.authConfig.token&&(this.user=void 0,this.userPromise=void 0,this.teams=void 0,this.teamsPromise=void 0),this.authConfig={...this.authConfig,...authConfig}}emptyAuthConfig(){this.user=void 0,this.userPromise=void 0,this.teams=void 0,this.teamsPromise=void 0,this.authConfig=this.authConfig.skipWrite?{skipWrite:!0}:{}}persistAuthConfig(){persistAuthConfig(this.authConfig,this.config)}async confirmMutatingOperation(url,method){if(!((method||"GET").toUpperCase()==="DELETE"))return!0;if(this.isAgent&&this.dangerouslySkipPermissions){let agentInfo=this.agentName?` (${this.agentName})`:"";output_manager_default.print(`
|
|
10
10
|
`),output_manager_default.print((0,import_chalk2.bgRed)((0,import_chalk2.white)((0,import_chalk2.bold)(" \u26A0 WARNING ")))+(0,import_chalk2.red)((0,import_chalk2.bold)(` AGENT MODE - DELETE CONFIRMATION BYPASSED
|
|
11
11
|
`))),output_manager_default.print((0,import_chalk2.yellow)(` An AI agent${agentInfo} is executing a ${(0,import_chalk2.bold)("DELETE")} request with --dangerously-skip-permissions flag.
|
|
12
12
|
`)),output_manager_default.print((0,import_chalk2.yellow)(` This operation will delete data: ${(0,import_chalk2.bold)(url)}
|
|
@@ -17,4 +17,4 @@ ${error.stack}`)};this.setArgv(opts.argv),this.apiUrl=opts.apiUrl,this.authConfi
|
|
|
17
17
|
|
|
18
18
|
Are you sure you want to proceed?`;output_manager_default.print(`
|
|
19
19
|
`);let confirmed=await this.input.confirm(message,!1);return output_manager_default.print(`
|
|
20
|
-
`),confirmed||output_manager_default.log("Operation canceled by user."),confirmed}async _fetch(_url,opts={}){let url=new URL(_url,this.apiUrl);(opts.accountId||opts.useCurrentTeam!==!1)&&(opts.accountId?opts.accountId.startsWith("team_")?url.searchParams.set("teamId",opts.accountId):url.searchParams.delete("teamId"):opts.useCurrentTeam!==!1&&this.config.currentTeam&&!url.searchParams.has("teamId")&&url.searchParams.set("teamId",this.config.currentTeam));let headers=new globalThis.Headers(opts.headers);headers.set("user-agent",ua_default),DOMAINS_API_PATH.test(url.pathname)&&headers.set("x-vercel-cli-version",pkg_default.version),this.agentName&&headers.set("x-ai-agent",this.agentName),headers.set("x-vercel-cli-session-id",this.telemetryEventStore.currentSessionId),headers.set("x-vercel-cli-invocation-id",this.telemetryEventStore.currentInvocationId),await this.ensureAuthorized(),this.authConfig.token&&headers.set("authorization",`Bearer ${this.authConfig.token}`);let body;isJSONObject(opts.body)?(body=JSON.stringify(opts.body),headers.set("content-type","application/json; charset=utf-8")):body=opts.body;let requestId=this.requestIdCounter++;return output_manager_default.time(res=>res?`#${requestId} \u2190 ${res.status} ${res.statusText}: ${res.headers.get("x-vercel-id")}`:`#${requestId} \u2192 ${opts.method||"GET"} ${url.href}`,fetch(url,{...opts,headers,body}))}fetch(url,opts={}){return this.retry(async bail=>{let res;try{res=await this._fetch(url,opts)}catch(err){if(err instanceof Error&&(err.name==="AbortError"||err.name==="TimeoutError"))return bail(err);throw err}if(printIndications(res),!res.ok){if(opts.redirect==="manual"&&res.status>=300&&res.status<400)return res;let error=await responseError(res);if(isSAMLError(error)&&error.teamId)try{await this.reauthenticate(error)}catch(reauthError){return bail((0,
|
|
20
|
+
`),confirmed||output_manager_default.log("Operation canceled by user."),confirmed}async _fetch(_url,opts={}){let url=new URL(_url,this.apiUrl);(opts.accountId||opts.useCurrentTeam!==!1)&&(opts.accountId?opts.accountId.startsWith("team_")?url.searchParams.set("teamId",opts.accountId):url.searchParams.delete("teamId"):opts.useCurrentTeam!==!1&&this.config.currentTeam&&!url.searchParams.has("teamId")&&url.searchParams.set("teamId",this.config.currentTeam));let headers=new globalThis.Headers(opts.headers);headers.set("user-agent",ua_default),DOMAINS_API_PATH.test(url.pathname)&&headers.set("x-vercel-cli-version",pkg_default.version),this.agentName&&headers.set("x-ai-agent",this.agentName),headers.set("x-vercel-cli-session-id",this.telemetryEventStore.currentSessionId),headers.set("x-vercel-cli-invocation-id",this.telemetryEventStore.currentInvocationId),await this.ensureAuthorized(),this.authConfig.token&&headers.set("authorization",`Bearer ${this.authConfig.token}`);let body;isJSONObject(opts.body)?(body=JSON.stringify(opts.body),headers.set("content-type","application/json; charset=utf-8")):body=opts.body;let requestId=this.requestIdCounter++;return output_manager_default.time(res=>res?`#${requestId} \u2190 ${res.status} ${res.statusText}: ${res.headers.get("x-vercel-id")}`:`#${requestId} \u2192 ${opts.method||"GET"} ${url.href}`,fetch(url,{...opts,headers,body}))}fetch(url,opts={}){return this.retry(async bail=>{let res;try{res=await this._fetch(url,opts)}catch(err){if(err instanceof Error&&(err.name==="AbortError"||err.name==="TimeoutError"))return bail(err);throw err}if(printIndications(res),!res.ok){if(opts.redirect==="manual"&&res.status>=300&&res.status<400)return res;let error=await responseError(res);if(isSAMLError(error)&&error.teamId)try{await this.reauthenticate(error)}catch(reauthError){return bail((0,import_error_utils.normalizeError)(reauthError))}else{if(res.status===429&&opts.bailOn429)return bail(error);if(typeof error.retryAfterMs=="number"){let randomSkewMs=3e4*Math.random();await sleep(error.retryAfterMs+randomSkewMs)}else if(res.status>=400&&res.status<500)return bail(error)}throw error}if(opts.json===!1)return res;let contentType=res.headers.get("content-type");return contentType?contentType.includes("application/json")?res.json():res:null},opts.retry)}async*fetchPaginated(url,opts){let endpoint=typeof url=="string"?new URL(url,this.apiUrl):new URL(url.href);endpoint.searchParams.has("limit")||endpoint.searchParams.set("limit","100");let next;do{next&&(await sleep(100),endpoint.searchParams.set("until",String(next)));let res=await this.fetch(endpoint.href,opts);yield res,next=res.pagination?.next}while(next)}get cwd(){return process.cwd()}set cwd(v){process.chdir(v)}};export{printIndications,isJSONObject,isValidAccessToken,Client};
|
|
@@ -25,7 +25,7 @@ ${MANAGED_BLOCK_END}`,existing=current??"",start=existing.indexOf(MANAGED_BLOCK_
|
|
|
25
25
|
|
|
26
26
|
`;return`${existing}${prefix}${block}
|
|
27
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 stat3=await fs.stat(path);(!best||stat3.mtimeMs>best.mtime)&&(best={path,mtime:stat3.mtimeMs})}catch{}}return best?.path??null}async function readRecord(path){let stat3;try{stat3=await fs.stat(path)}catch{return null}if(!stat3.isFile()||stat3.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:stat3.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"},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."]}}};var PREFS_FILE="agent-preferences.json",CLAUDE_LEGACY_PLUGIN_ID="vercel-plugin@vercel",CLAUDE_OFFICIAL_PLUGIN_ID="vercel@claude-plugins-official",VERCEL_PLUGIN_VERSION_URL="https://raw.githubusercontent.com/vercel/vercel-plugin/main/.claude-plugin/plugin.json",AGENT_TO_TARGET={[KNOWN_AGENTS.CLAUDE]:"claude-code",[KNOWN_AGENTS.COWORK]:"claude-code"};function getPluginTargetForAgent(agentName){if(agentName)return agentName===KNOWN_AGENTS.CLAUDE||agentName.startsWith("claude-code")||agentName===KNOWN_AGENTS.COWORK?"claude-code":AGENT_TO_TARGET[agentName]}var promptedAtSchema=z.codec(z.union([z.iso.date(),z.iso.datetime()]),z.date(),{decode:value=>new Date(value),encode:value=>value.toISOString()}),agentPreferencesSchema=z.object({pluginDeclined:z.boolean().optional(),pluginAutoUpdate:z.boolean().optional(),lastPromptedAt:promptedAtSchema.optional(),lastPluginAutoUpdateAttemptedAt:promptedAtSchema.optional(),lastPluginAutoUpdateAttemptedKey:z.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{}}function encodeClaudeProjectDir(projectPath){return projectPath.replace(/[^A-Za-z0-9]/g,"-")}async function projectHasUsedClaudeCode(cwd){let home=homedir(),projectsDir=join3(home,".claude","projects"),dir=resolve(cwd);for(;dir!==home;){if(await fileExists(join3(projectsDir,encodeClaudeProjectDir(dir))))return!0;let parent=dirname3(dir);if(parent===dir)break;dir=parent}return!1}async function getPluginTargets(agentName,cwd){let targetForAgent=getPluginTargetForAgent(agentName);return targetForAgent?[targetForAgent]:agentName?[]:cwd&&await projectHasUsedClaudeCode(cwd)?["claude-code"]:[]}async function readClaudeInstalledPluginsFromRegistry(){try{let raw=await readFile3(getClaudeInstalledPluginsRegistryPath(),"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)}
|
|
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."]}}};var PREFS_FILE="agent-preferences.json",CLAUDE_LEGACY_PLUGIN_ID="vercel-plugin@vercel",CLAUDE_OFFICIAL_PLUGIN_ID="vercel@claude-plugins-official",VERCEL_PLUGIN_VERSION_URL="https://raw.githubusercontent.com/vercel/vercel-plugin/main/.claude-plugin/plugin.json",AGENT_TO_TARGET={[KNOWN_AGENTS.CLAUDE]:"claude-code",[KNOWN_AGENTS.COWORK]:"claude-code"};function getPluginTargetForAgent(agentName){if(agentName)return agentName===KNOWN_AGENTS.CLAUDE||agentName.startsWith("claude-code")||agentName===KNOWN_AGENTS.COWORK?"claude-code":AGENT_TO_TARGET[agentName]}var promptedAtSchema=z.codec(z.union([z.iso.date(),z.iso.datetime()]),z.date(),{decode:value=>new Date(value),encode:value=>value.toISOString()}),agentPreferencesSchema=z.object({pluginDeclined:z.boolean().optional(),pluginAutoUpdate:z.boolean().optional(),lastPromptedAt:promptedAtSchema.optional(),lastPluginAutoUpdateAttemptedAt:promptedAtSchema.optional(),lastPluginAutoUpdateAttemptedKey:z.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{}}function encodeClaudeProjectDir(projectPath){return projectPath.replace(/[^A-Za-z0-9]/g,"-")}async function projectHasUsedClaudeCode(cwd){let home=homedir(),projectsDir=join3(home,".claude","projects"),dir=resolve(cwd);for(;dir!==home;){if(await fileExists(join3(projectsDir,encodeClaudeProjectDir(dir))))return!0;let parent=dirname3(dir);if(parent===dir)break;dir=parent}return!1}async function getPluginTargets(agentName,cwd){let targetForAgent=getPluginTargetForAgent(agentName);return targetForAgent?[targetForAgent]:agentName?[]:cwd&&await projectHasUsedClaudeCode(cwd)?["claude-code"]:[]}async function readClaudeInstalledPluginsFromRegistry(){try{let raw=await readFile3(getClaudeInstalledPluginsRegistryPath(),"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
29
|
`,"utf-8"),!0)}catch(err){return output_manager_default.debug(`Failed to remove Claude plugin registry entry: ${err}`),!1}}async function isPluginInstalledForTarget(target){return target==="claude-code"?(await getClaudePluginStatus()).state==="official-only":!1}async function confirm(client,message){return client.nonInteractive||!client.stdin.isTTY?!1:client.input.confirm(message,!0)}function isSameDay(left,right){return left.getFullYear()===right.getFullYear()&&left.getMonth()===right.getMonth()&&left.getDate()===right.getDate()}function wasPromptedToday(prefs){return prefs.lastPromptedAt?isSameDay(prefs.lastPromptedAt,new Date):!1}function wasPluginAutoUpdateAttemptedToday(prefs,attemptKey){return prefs.lastPluginAutoUpdateAttemptedKey===attemptKey&&!!prefs.lastPluginAutoUpdateAttemptedAt&&isSameDay(prefs.lastPluginAutoUpdateAttemptedAt,new Date)}async function markPromptedToday(client,prefs){prefs.lastPromptedAt=new Date,await writePrefs(client,prefs)}function markPluginAutoUpdateAttempted(prefs,attemptKey){attemptKey&&(prefs.lastPluginAutoUpdateAttemptedAt=new Date,prefs.lastPluginAutoUpdateAttemptedKey=attemptKey)}async function runCommand(command,args){return await new Promise(resolve2=>{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=>{resolve2({exitCode:code??1,stdout,stderr})}),child.on("error",err=>{resolve2({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 parse2=value=>value.split(".").map(part=>Number.parseInt(part,10)||0),left=parse2(a),right=parse2(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 getClaudeAutoUpdateAttemptKey(status,plan){return[status.state,status.legacy?.version??"none",status.official?.version??"none",status.latestVersion??"unknown",plan.installOfficial?"install":"",plan.updateOfficial?"update":"",plan.removeLegacy?"remove-legacy":"",plan.removeLegacyMarketplace?"remove-marketplace":""].join(":")}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
30
|
${result.stderr||result.stdout}`),!1)}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 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)}async function applyPluginActions(targets,claudePlan){for(let target of targets)target==="claude-code"&&claudePlan?await runClaudeMigration(claudePlan):output_manager_default.debug(`Skipping unsupported plugin target: ${target}`)}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
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:status.latestVersion});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}.`}}async function autoInstallVercelPlugin(client,options){try{let prefs=await readPrefs(client),applyMode=options?.mode==="apply";if(!prefs.pluginDeclined||prefs.pluginAutoUpdate||applyMode){let targets=await getPluginTargets(client.agentName,client.cwd),uninstalledTargets=[],claudeStatus=targets.includes("claude-code")?await getClaudePluginStatus():void 0,claudePlan=claudeStatus?buildClaudePluginMigrationPlan(claudeStatus):void 0,claudeAutoUpdateAttemptKey=claudeStatus&&claudePlan?getClaudeAutoUpdateAttemptKey(claudeStatus,claudePlan):void 0;for(let target of targets){if(target==="claude-code"){claudePlan&&hasClaudeMigrationActions(claudePlan)&&uninstalledTargets.push(target);continue}await isPluginInstalledForTarget(target)||uninstalledTargets.push(target)}if(uninstalledTargets.length>0){if(prefs.pluginAutoUpdate){if(claudeAutoUpdateAttemptKey&&wasPluginAutoUpdateAttemptedToday(prefs,claudeAutoUpdateAttemptKey))return;prefs.pluginDeclined=!1,markPluginAutoUpdateAttempted(prefs,claudeAutoUpdateAttemptKey),await writePrefs(client,prefs),await applyPluginActions(uninstalledTargets,claudePlan);return}if(!applyMode&&wasPromptedToday(prefs))return;if(applyMode){prefs.pluginDeclined=!1,prefs.pluginAutoUpdate=!0,await writePrefs(client,prefs),await applyPluginActions(uninstalledTargets,claudePlan);return}let promptMessages=[],confirmMessage="Install the Vercel plugin?";if(uninstalledTargets.includes("claude-code")&&claudeStatus&&claudePlan){let claudePrompt=buildClaudePromptCopy(claudeStatus,claudePlan);promptMessages.push(claudePrompt.message),confirmMessage=claudePrompt.confirm}let promptMessage=promptMessages.join(" ").trim();promptMessage&&output_manager_default.log(promptMessage);let accepted=await confirm(client,confirmMessage);await markPromptedToday(client,prefs),accepted?(prefs.pluginDeclined=!1,prefs.pluginAutoUpdate=!0,await writePrefs(client,prefs),await applyPluginActions(uninstalledTargets,claudePlan)):(prefs.pluginDeclined=!0,prefs.pluginAutoUpdate=!1,await writePrefs(client,prefs))}}}catch(err){output_manager_default.debug(`Auto-install agent tooling failed: ${err}`)}}export{pathExists,isFile,isSymlink,readFileOrNull,parseJsonObjectOrNull,mergeJson,mergeJsonc,mergeToml,MANAGED_BLOCK_START,MANAGED_BLOCK_END,upsertManagedBlock,publishNoClobber,ensureMode,backupFile,writeConfigFile,GATEWAY_ANTHROPIC_BASE_URL,GATEWAY_CODING_AGENT_BASE_URL,GATEWAY_CURSOR_BASE_URL,GATEWAY_CODEX_BASE_URL,GATEWAY_API_KEY_ENV,GATEWAY_DEFAULT_MODEL,KEY_PLACEHOLDER,resolveGatewayBaseUrl,maskSecret,claudeCode,setupVercelPlugin,autoInstallVercelPlugin};
|
|
@@ -0,0 +1,9 @@
|
|
|
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{buildCorrectedCommand,isArgumentError}from"./chunk-WWB66KP5.js";import{getErrorRecovery,shouldEmitNonInteractiveCommandError,trackAgentError,writeAgentError}from"./chunk-KCARCOP5.js";import{parseRetryAfterHeaderAsMillis,require_bytes}from"./chunk-RINZXCDJ.js";import{getCommandName}from"./chunk-FI772UVH.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{pkg_default}from"./chunk-AVSPFBLM.js";import{require_source}from"./chunk-U7KCDTCH.js";import{__toESM}from"./chunk-6L236MNA.js";var import_chalk=__toESM(require_source(),1);var import_bytes=__toESM(require_bytes(),1);async function responseError(res,fallbackMessage=null,parsedBody={}){let message="",bodyError;if(res.status>=400&&res.status<500){let body;try{body=await res.json()}catch{body=parsedBody}bodyError=body.error||body.err||{},message=bodyError.message}message||(message=fallbackMessage===null?"Response Error":fallbackMessage);let err=new Error(`${message} (${res.status})`);if(err.status=res.status,err.serverMessage=message,bodyError)for(let field of Object.keys(bodyError))field!=="message"&&(err[field]=bodyError[field]);if(res.status===429||res.status===503){let parsed=parseRetryAfterHeaderAsMillis(res.headers.get("Retry-After"));err.retryAfterMs=parsed??(res.status===429?0:void 0)}return err}function toEnumerableError(err){let enumerable={};enumerable.name=err.name;for(let key of Object.getOwnPropertyNames(err))enumerable[key]=err[key];return enumerable}function printError(error2,client){typeof error2=="string"&&(error2=new Error(error2));let apiError=error2,{message,stack,status,code,sizeLimit}=apiError,argumentError=isArgumentError(error2)?error2:void 0,suggestion=argumentError?.suggestedOption&&argumentError.invalidOption,correction=suggestion&&client&&argumentError?buildCorrectedCommand(client.argv,argumentError.invalidOption,argumentError.suggestedOption,argumentError.flagsSpecification):void 0,recovery=getErrorRecovery(apiError,client),reason=status===403?"forbidden":status===402?"payment_required":status===401?"not_authorized":status===429?"rate_limited":code==="ARG_UNKNOWN_OPTION"?"invalid_arguments":"api_error",hint=argumentError?.allowedOptions?`Vercel CLI ${pkg_default.version} accepts: ${argumentError.allowedOptions.join(", ")}.${suggestion?` Did you mean ${argumentError.suggestedOption}?`:""}`:recovery.hint;if(client&&(status||argumentError?.allowedOptions)){let payload={...recovery,status:"error",reason,message:apiError.serverMessage||message,hint,...argumentError?.allowedOptions&&{allowedOptions:argumentError.allowedOptions,suggestedOption:argumentError.suggestedOption,cliVersion:pkg_default.version},...correction&&{next:[{command:correction,when:correction.includes("<")?"Replace placeholders with the intended values, then run the corrected command":"Run the corrected command"}]}};if(shouldEmitNonInteractiveCommandError(client)){output_manager_default.stopSpinner(),writeAgentError(client,payload);return}trackAgentError(client,payload)}if(hint){output_manager_default.stopSpinner(),output_manager_default.fatal(apiError.serverMessage||message||"The request failed."),output_manager_default.print(` ${hint}
|
|
8
|
+
`),correction&&output_manager_default.print(` ${correction}
|
|
9
|
+
`);return}output_manager_default.debug(`handling error: ${stack}`),message!=="User force closed the prompt with 0 null"&&(status===403?output_manager_default.error(message||`Authentication error. Run ${getCommandName("login")} to log-in again.`):status===429?output_manager_default.error(message):code==="size_limit_exceeded"?output_manager_default.error(`File size limit exceeded (${(0,import_bytes.default)(sizeLimit)})`):message?output_manager_default.prettyError(apiError):status===500?output_manager_default.error("Unexpected server error. Please retry."):code==="USER_ABORT"?output_manager_default.log("Canceled"):output_manager_default.error(`Unexpected error. Please try again later. (${message})`))}export{responseError,toEnumerableError,printError};
|
|
@@ -4,6 +4,6 @@ import { dirname as __dirname_ } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
const __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
const __dirname = __dirname_(__filename);
|
|
7
|
-
import{require_dist}from"./chunk-TRTEXGVN.js";import{getDeployment}from"./chunk-
|
|
7
|
+
import{require_dist}from"./chunk-TRTEXGVN.js";import{getDeployment}from"./chunk-C5KVTG2O.js";import{getScope}from"./chunk-LFQTA3CF.js";import{toNodeReadable}from"./chunk-MY4MONOH.js";import{output_manager_default}from"./chunk-EWWFNMPZ.js";import{require_ansi_escapes}from"./chunk-7HL2RPUO.js";import{__commonJS,__require,__toESM}from"./chunk-6L236MNA.js";var require_parser=__commonJS({"../../node_modules/.pnpm/jsonlines@0.1.1/node_modules/jsonlines/lib/parser.js"(exports,module){var Transform=__require("stream").Transform;function Parser(options){if(!(this instanceof Parser))throw new TypeError("Cannot call a class as a function");options=options||{},Transform.call(this,{objectMode:!0}),this._memory="",this._emitInvalidLines=options.emitInvalidLines||!1}Parser.prototype=Object.create(Transform.prototype);Parser.prototype._handleLines=function(lines,cb){for(var i=0;i<lines.length;i++)if(lines[i]!==""){var err=null,json=null;try{json=JSON.parse(lines[i])}catch(_err){_err.source=lines[i],err=_err}if(err)if(this._emitInvalidLines)this.emit("invalid-line",err);else return cb(err);else this.push(json)}cb(null)};Parser.prototype._transform=function(chunk,encoding,cb){var lines=(this._memory+chunk.toString()).split(`
|
|
8
8
|
`);this._memory=lines.pop(),this._handleLines(lines,cb)};Parser.prototype._flush=function(cb){if(!this._memory)return cb(null);var line=this._memory;this._memory="",this._handleLines([line],cb)};module.exports=Parser}});var require_stringifier=__commonJS({"../../node_modules/.pnpm/jsonlines@0.1.1/node_modules/jsonlines/lib/stringifier.js"(exports,module){var Transform=__require("stream").Transform;function Stringifier(){if(!(this instanceof Stringifier))throw new TypeError("Cannot call a class as a function");Transform.call(this,{objectMode:!0})}Stringifier.prototype=Object.create(Transform.prototype);Stringifier.prototype._transform=function(data,_,cb){var value;try{value=JSON.stringify(data)}catch(err){return err.source=data,cb(err)}cb(null,value+`
|
|
9
9
|
`)};module.exports=Stringifier}});var require_jsonlines=__commonJS({"../../node_modules/.pnpm/jsonlines@0.1.1/node_modules/jsonlines/index.js"(exports){var Parser=require_parser(),Stringifier=require_stringifier();exports.parse=function(options){return new Parser(options)};exports.stringify=function(){return new Stringifier}}});var import_async_retry=__toESM(require_dist(),1),import_jsonlines=__toESM(require_jsonlines(),1),import_ansi_escapes=__toESM(require_ansi_escapes(),1);import{URLSearchParams}from"url";async function printEvents(client,urlOrDeploymentId,{mode,onEvent,onAliasAssigned,quiet,findOpts},abortController){let{log,debug}=output_manager_default,scope=mode==="deploy"?await getScope(client):null,o=0;await(0,import_async_retry.default)(async(bail,attemptNumber)=>{attemptNumber>1&&debug("Retrying events");let query=new URLSearchParams({direction:findOpts.direction,follow:findOpts.follow?"1":"",format:"lines"});findOpts.limit&&query.set("limit",String(findOpts.limit)),findOpts.since&&query.set("since",String(findOpts.since)),findOpts.until&&query.set("until",String(findOpts.until));let eventsUrl=`/v3/now/deployments/${urlOrDeploymentId}/events?${query}`;try{let eventsRes=await client.fetch(eventsUrl,{json:!1,signal:abortController?.signal});if(eventsRes.ok){let readable=toNodeReadable(eventsRes.body);return new Promise((resolve,reject)=>{let stream=readable.pipe(import_jsonlines.default.parse()),poller;mode==="deploy"&&(poller=function startPoller(){return setTimeout(async()=>{try{if((await getDeployment(client,scope.contextName,urlOrDeploymentId)).readyState==="READY"){stream.end(),finish();return}poller=startPoller()}catch(err2){stream.end(),finish(err2)}},5e3)}());let finishCalled=!1;function finish(err2){finishCalled||(finishCalled=!0,clearTimeout(poller),err2?reject(err2):resolve())}let latestLogDate=0,onData=data=>{if(data.type==="alias-assigned"){data.deploymentId===urlOrDeploymentId&&onAliasAssigned?.(data);return}let{event,payload,date}=data;event==="state"&&payload.value==="READY"?mode==="deploy"&&(stream.end(),finish()):(latestLogDate=Math.max(latestLogDate,date),onEvent(data))},onErrorCalled=!1,onError=err2=>{if(finishCalled||onErrorCalled)return;if(err2.name==="AbortError"){finish();return}onErrorCalled=!0,o++;let errorMessage=`Deployment event stream error: ${err2.message}`;if(!findOpts.follow){log(errorMessage);return}debug(errorMessage),clearTimeout(poller),stream.destroy(err2);let retryFindOpts={...findOpts,since:latestLogDate},retryTimeout=setTimeout(()=>{abortController?.signal.removeEventListener("abort",onAbort),!abortController?.signal.aborted&&printEvents(client,urlOrDeploymentId,{mode,onEvent,onAliasAssigned,quiet,findOpts:retryFindOpts},abortController).then(resolve,reject)},2e3),onAbort=()=>{clearTimeout(retryTimeout),finish()};abortController?.signal.addEventListener("abort",onAbort,{once:!0})};stream.on("end",finish),stream.on("data",onData),stream.on("error",onError),readable.on("error",onError)})}let err=new Error(`Deployment events status ${eventsRes.status}`);if(eventsRes.status<500)bail(err);else throw err}catch(err){if(err instanceof Error&&err.name==="AbortError")return;throw err}},{retries:4,unref:!!onAliasAssigned,onRetry:err=>{!quiet&&o&&(process.stdout.write((0,import_ansi_escapes.eraseLines)(o+1)),o=0),log(`Deployment events polling error: ${err.message}`)}})}var events_default=printEvents;export{require_jsonlines,events_default};
|