import{captureVercel}from"./primitives/run-vercel.js";import{join}from"node:path";import{readFile}from"node:fs/promises";function pickShortestAlias(e){if(!Array.isArray(e))return;let t;for(let n of e)typeof n!=`string`||n.length===0||(t===void 0||n.length<t.length)&&(t=n);return t}async function fetchProductionAlias(t,n,r){let i=await captureVercel([`api`,`/v9/projects/${t}?teamId=${n}`,`--scope`,n],{cwd:r});if(i.ok)try{let e=pickShortestAlias(JSON.parse(i.stdout).targets?.production?.alias);return e?`https://${e}`:void 0}catch{return}}async function detectDeployment(e){let r;try{r=await readFile(join(e,`.vercel`,`project.json`),`utf8`)}catch{return{state:`unlinked`}}let i;try{i=JSON.parse(r)}catch{return{state:`unlinked`}}let a=typeof i.projectId==`string`?i.projectId:void 0,o=typeof i.orgId==`string`?i.orgId:void 0;if(!a||!o)return{state:`unlinked`};let s=await fetchProductionAlias(a,o,e);return{state:s?`deployed`:`linked`,projectId:a,orgId:o,productionUrl:s}}function projectResolutionFromDeployment(e){return e.state===`unlinked`||e.projectId===void 0?{kind:`unresolved`}:e.state===`deployed`&&e.productionUrl!==void 0?{kind:`deployed`,projectId:e.projectId,productionUrl:e.productionUrl}:{kind:`linked`,projectId:e.projectId}}async function detectProjectResolution(e){return projectResolutionFromDeployment(await detectDeployment(e))}function mergeProjectResolution(e,t){return t.kind===`unresolved`||e.kind===`deployed`&&e.projectId===t.projectId?e:t}function projectResolutionFromDeployResult(e,t){return e.kind===`unresolved`||!t.deployed||t.productionUrl===void 0?e:{kind:`deployed`,projectId:e.projectId,productionUrl:t.productionUrl}}function isProjectResolved(e){return e.kind!==`unresolved`}function projectProductionUrlFromResolution(e){return e.kind===`deployed`?e.productionUrl:void 0}export{detectDeployment,detectProjectResolution,isProjectResolved,mergeProjectResolution,projectProductionUrlFromResolution,projectResolutionFromDeployResult,projectResolutionFromDeployment};