import{t as e}from"./rolldown-runtime-CNxR59P3.js";import{g as t}from"./paths-B4IRk3wi.js";import n from"node:fs";import r from"node:path";function i(e){try{if(!n.existsSync(e))return;let t=n.readFileSync(e,`utf8`);return JSON.parse(t)}catch{return}}function a(e,t){let i=r.dirname(e);n.existsSync(i)||n.mkdirSync(i,{recursive:!0,mode:448}),n.writeFileSync(e,`${JSON.stringify(t,null,2)}\n`,`utf8`),n.chmodSync(e,384)}var o=e({DEFAULT_COPILOT_API_BASE_URL:()=>d,deriveCopilotApiBaseUrlFromToken:()=>f,resolveCopilotApiToken:()=>p});const s=`https://api.github.com/copilot_internal/v2/token`;function c(e=process.env){return r.join(t(e),`credentials`,`github-copilot.token.json`)}function l(e,t=Date.now()){return e.expiresAt-t>300*1e3}function u(e){if(!e||typeof e!=`object`)throw Error(`Unexpected response from GitHub Copilot token endpoint`);let t=e,n=t.token,r=t.expires_at;if(typeof n!=`string`||n.trim().length===0)throw Error(`Copilot token response missing token`);let i;if(typeof r==`number`&&Number.isFinite(r))i=r>1e10?r:r*1e3;else if(typeof r==`string`&&r.trim().length>0){let e=Number.parseInt(r,10);if(!Number.isFinite(e))throw Error(`Copilot token response has invalid expires_at`);i=e>1e10?e:e*1e3}else throw Error(`Copilot token response missing expires_at`);return{token:n,expiresAt:i}}const d=`https://api.individual.githubcopilot.com`;function f(e){let t=e.trim();if(!t)return null;let n=t.match(/(?:^|;)\s*proxy-ep=([^;\s]+)/i)?.[1]?.trim();if(!n)return null;let r=n.replace(/^https?:\/\//,``).replace(/^proxy\./i,`api.`);return r?`https://${r}`:null}async function p(e){let t=e.env??process.env,n=e.cachePath?.trim()||c(t),r=e.loadJsonFileImpl??i,o=e.saveJsonFileImpl??a,d=r(n);if(d&&typeof d.token==`string`&&typeof d.expiresAt==`number`&&l(d))return{token:d.token,expiresAt:d.expiresAt,source:`cache:${n}`,baseUrl:f(d.token)??`https://api.individual.githubcopilot.com`};let p=await(e.fetchImpl??fetch)(s,{method:`GET`,headers:{Accept:`application/json`,Authorization:`Bearer ${e.githubToken}`}});if(!p.ok)throw Error(`Copilot token exchange failed: HTTP ${p.status}`);let m=u(await p.json()),h={token:m.token,expiresAt:m.expiresAt,updatedAt:Date.now()};return o(n,h),{token:h.token,expiresAt:h.expiresAt,source:`fetched:${s}`,baseUrl:f(h.token)??`https://api.individual.githubcopilot.com`}}export{a,i,o as n,p as r,d as t};
