openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 13.8 kB
JavaScript
import{m as readNonBlankString}from"./string-coerce-CpTFcSwY.mjs";import{E as parseStrictNonNegativeInteger,s as asFiniteNumber}from"./number-coercion-B3CfI447.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{n as materializeErrorStack}from"./error-graph-internal-Bt2pFJBM.mjs";import{t as pruneMapToMaxSize}from"./map-size-DLQqorvK.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{i as readResponseWithLimit}from"./http-response-body-BJ35MG8h.mjs";import{t as parseRetryAfterHeaderSeconds}from"./retry-after-C51cpEfp.mjs";import"./string-coerce-runtime-BYDH9Quw.mjs";import"./retry-runtime-IpBUqeJt.mjs";import"./error-runtime-DW-sj0iq.mjs";import"./response-limit-runtime-uUJhFwkj.mjs";import"./diagnostic-runtime-CjeXdjZk.mjs";import{createHash}from"node:crypto";
//!extensions/github/src/github-api.ts
const DEFAULT_GITHUB_API_BASE_URL=`https://api.github.com`;const GITHUB_API_ORIGIN=DEFAULT_GITHUB_API_BASE_URL;function resolveGitHubApiBaseUrl(e){const t=e?.trim()||DEFAULT_GITHUB_API_BASE_URL;const n=new URL(t);if(n.protocol!==`https:`||n.username||n.password||n.search||n.hash||![`/`,``,`/api/v3`,`/api/v3/`].includes(n.pathname))throw new Error(`gateway.github.apiBaseUrl must be an HTTPS GitHub API base URL`);return n.origin+(n.pathname.startsWith(`/api/v3`)?`/api/v3`:``)}const GITHUB_API_BASE_URL=DEFAULT_GITHUB_API_BASE_URL;function githubGraphqlUrl(e){return e.endsWith(`/api/v3`)?`${e.slice(0,-3)}/graphql`:`${e}/graphql`}const GITHUB_GRAPHQL_URL=githubGraphqlUrl(GITHUB_API_BASE_URL);function resolveGitHubApiUrls(e){const t=resolveGitHubApiBaseUrl(e);return{baseUrl:t,graphqlUrl:githubGraphqlUrl(t)}}function githubRestApiPath(e,t=GITHUB_API_BASE_URL){const n=new URL(t).pathname;return e.pathname.slice(n===`/`?0:n.length)}const GITHUB_JSON_MAX_BYTES=262144;const GITHUB_REQUEST_TIMEOUT_MS=8e3;const GITHUB_API_VERSION=`2022-11-28`;const GITHUB_API_MAX_REDIRECTS=3;const GITHUB_QUOTA_CACHE_LIMIT=200;const GITHUB_QUOTA_RETRY_MS=6e4;const log=createSubsystemLogger(`github/http`);const transportCooldowns=/* @__PURE__ */ new WeakMap;const responseRequestScopes=/* @__PURE__ */ new WeakMap;var ControlUiGitHubError=class extends Error{constructor(e,t,n={}){super(t);this.statusCode=e;this.name=`ControlUiGitHubError`;this.upstreamStatus=n.upstreamStatus??e;this.retryAtMs=n.retryAtMs;this.retryable=n.retryable??(e===429||n.upstreamStatus!==void 0&&n.upstreamStatus>=500)}get retryAfterMs(){return this.retryAtMs===void 0?void 0:Math.max(0,this.retryAtMs-Date.now())}};var ControlUiGitHubTransportError=class extends ControlUiGitHubError{constructor(e){super(502,e,{retryable:true})}};var GitHubGraphQLUnavailableError=class extends ControlUiGitHubError{constructor(e){super(403,`GitHub GraphQL access is unavailable for the selected credential`,{upstreamStatus:e,retryable:false})}};function formatControlUiGitHubPreviewError(e){if(e instanceof ControlUiGitHubTransportError)return{message:`${e.message}. Retry or check GitHub availability.`,retryable:true};if(e instanceof ControlUiGitHubError){const t=`HTTP ${e.upstreamStatus}`;switch(e.statusCode){case 401:return{message:`GitHub authentication failed (${t}). Reconnect the GitHub identity in Settings.`,retryable:false};case 403:return{message:`GitHub access denied (${t}). Check the configured GitHub identity's repository access.`,retryable:false};case 404:return{message:`GitHub item is unavailable or not public (HTTP 404). Open the link on GitHub to check access.`,retryable:false};case 429:{const n=e.retryAfterMs;return{message:`GitHub API rate limit exceeded (${t}). ${n===void 0?`Wait`:`Wait ${Math.ceil(n/1e3)} seconds`} and retry.`,retryable:true,...n===void 0?{}:{retryAfterMs:n}}}case 502:return{message:`${e.message.slice(0,256)}. Retry or check GitHub availability.`,retryable:true}}}if(e instanceof Error&&(e.name===`TimeoutError`||e.name===`AbortError`))return{message:`GitHub request timed out. Retry shortly.`,retryable:true};return{message:`GitHub preview could not be loaded. Retry or check the server logs.`,retryable:false}}function githubApiCredentialCacheScope(e){return e?createHash(`sha256`).update(e).digest(`hex`):`anonymous`}function requiredString(e,t){const n=readNonBlankString(e[t]);if(n===void 0)throw new ControlUiGitHubError(502,`GitHub response omitted ${t}`);return n}function readOptionalGitHubString(e,t){return readNonBlankString(e[t])}function optionalNumber(e,t){return asFiniteNumber(e[t])}function githubApiResource(e,t,n){const r=githubRestApiPath(e,t);return e.href===n?`graphql`:r===`/search/code`?`code_search`:r.startsWith(`/search/`)?`search`:`core`}function retainGitHubCooldown(e,t,n,r,i){const a=transportCooldowns.get(e)??/* @__PURE__ */ new Map;transportCooldowns.set(e,a);const o=`${t}:${r.headers.get(`x-ratelimit-remaining`)===`0`?r.headers.get(`x-ratelimit-resource`)??n:`*`}`;const s=activeGitHubCooldown(a,o);const c=s&&(s.retryAfterMs??0)>(i.retryAfterMs??0)?s:i;materializeErrorStack(c);a.set(o,c);pruneMapToMaxSize(a,GITHUB_QUOTA_CACHE_LIMIT);return c}function activeGitHubCooldown(e,t){const n=e.get(t);if(n&&(n.retryAfterMs??0)<=0){e.delete(t);return}return n}function githubApiHeaders(e){const t={Accept:`application/vnd.github+json`,"User-Agent":`OpenClaw-Control-UI`,"X-GitHub-Api-Version":GITHUB_API_VERSION};if(e)t.Authorization=`Bearer ${e}`;return t}function isGitHubApiRedirect(e){return e===301||e===302||e===303||e===307||e===308}function safeGitHubApiUrl(e,t,n,r){const i=URL.parse(e,r);if(!i||i.origin!==t.origin||i.username||i.password||i.href!==n&&!i.pathname.startsWith(`${t.pathname===`/`?``:t.pathname}/`))return null;return i}async function fetchGitHubApi(e,t,n,r,i,a,o,s,c=GITHUB_API_BASE_URL,l=`follow`){o?.throwIfAborted();i?.signal?.throwIfAborted();const u=resolveGitHubApiBaseUrl(c);const d=new URL(u);const f=githubGraphqlUrl(u);const p=safeGitHubApiUrl(e,d,f);if(!p)throw new ControlUiGitHubError(502,`Invalid GitHub API URL`);if(s&&(p.href!==f||!n||a))throw new ControlUiGitHubError(502,`Invalid authenticated GitHub GraphQL request`);let m=p;const h=`${u}:${githubApiCredentialCacheScope(n)}`;const g=transportCooldowns.get(t)??/* @__PURE__ */ new Map;transportCooldowns.set(t,g);const _=AbortSignal.timeout(GITHUB_REQUEST_TIMEOUT_MS);const v=AbortSignal.any([_,o,i?.signal].filter(e=>e!==void 0));for(let e=0;;e+=1){const c=performance.now();if(i){await i.revalidate();i.assertSelected()}const p=performance.now();const _=Math.round(p-c);o?.throwIfAborted();i?.signal?.throwIfAborted();const y=githubApiResource(m,u,f);const b=activeGitHubCooldown(g,`${h}:*`);const x=activeGitHubCooldown(g,`${h}:${y}`);const S=(b?.retryAfterMs??0)>(x?.retryAfterMs??0)?b:x;if(S)throw S;let C;try{C=await t(m.href,{headers:{...githubApiHeaders(n),...a&&e===0?{"If-None-Match":a}:{},...s?{"Content-Type":`application/json`}:{}},...s?{method:`POST`,body:JSON.stringify(s)}:{},redirect:`manual`,signal:v}).finally(()=>{const e=performance.now();if(_+e-p>=500)log.debug(`Slow GitHub API request`,{authMs:_,networkMs:Math.round(e-p),resource:y,aborted:v.aborted})})}catch(e){i?.signal?.throwIfAborted();i?.assertSelected();const t=v.aborted||e instanceof Error&&e.name===`TimeoutError`;throw new ControlUiGitHubTransportError(t?`GitHub request timed out`:`Could not reach GitHub`)}if(isGitHubRateLimitResponse(C)){const e=retainGitHubCooldown(t,h,y,C,githubResponseError(C));await discardResponse(C);throw e}if(!isGitHubApiRedirect(C.status)||l===`manual`){responseRequestScopes.set(C,{credentialScope:h,fetchImpl:t,resource:y});return C}const w=C.headers.get(`location`);const T=w?safeGitHubApiUrl(w,d,f,m):null;if(!T||e>=GITHUB_API_MAX_REDIRECTS){await discardResponse(C);throw new ControlUiGitHubError(502,`GitHub API returned an unsafe redirect`)}await discardResponse(C);await r?.(T);if(s)throw new ControlUiGitHubError(502,`GitHub GraphQL returned an unexpected redirect`);m=T}}async function discardResponse(e){e.body?.cancel().catch(()=>{})}async function readBoundedResponse(e,t){try{return await readResponseWithLimit(e,t,{onOverflow:()=>new ControlUiGitHubError(502,`GitHub response exceeded the size limit`)})}finally{await discardResponse(e)}}function isGitHubRateLimitResponse(e){if(e.status===429)return true;return e.status===403&&(e.headers.get(`x-ratelimit-remaining`)===`0`||e.headers.has(`retry-after`))}function githubResponseErrorStatus(e){if(isGitHubRateLimitResponse(e))return 429;if(e.status===401||e.status===403||e.status===404)return e.status;return 502}function githubResponseError(e,t=false){const n=t?429:githubResponseErrorStatus(e);let r;if(n===429){const t=Date.now();const n=parseRetryAfterHeaderSeconds(e.headers.get(`retry-after`));const i=e.headers.get(`x-ratelimit-remaining`)===`0`?parseStrictNonNegativeInteger(e.headers.get(`x-ratelimit-reset`)):void 0;const a=n!==void 0?t+n*1e3:i!==void 0&&i<=Number.MAX_SAFE_INTEGER/1e3?i*1e3:void 0;r=a!==void 0&&Number.isSafeInteger(a)&&Number.isFinite(new Date(a).getTime())&&a>t?a:t+GITHUB_QUOTA_RETRY_MS}return new ControlUiGitHubError(n,`GitHub request failed (HTTP ${e.status})`,{upstreamStatus:e.status,retryAtMs:r})}async function readGitHubGraphQLResponse(e,t,n,r){const i=responseRequestScopes.get(e)?.credentialScope??`${DEFAULT_GITHUB_API_BASE_URL}:${githubApiCredentialCacheScope(n)}`;const a=e.status===403&&!isGitHubRateLimitResponse(e)?(await readGitHubJsonBody(e,r)).value:await readGitHubJsonResponse(e,r);const o=isRecord(a)&&(a.data===void 0||a.data===null||isRecord(a.data)&&Object.values(a.data).every(e=>e===null));if(isRecord(a)&&a.errors!==void 0){if(Array.isArray(a.errors)&&a.errors.some(e=>isRecord(e)&&e.type===`RATE_LIMITED`))throw retainGitHubCooldown(t,i,`graphql`,e,githubResponseError(e,true));if(Array.isArray(a.errors)&&a.errors.length>0&&a.errors.every(e=>isRecord(e)&&(e.type===`FORBIDDEN`||e.type===`INSUFFICIENT_SCOPES`))&&o)throw new GitHubGraphQLUnavailableError(e.status);if(!Array.isArray(a.errors)||a.errors.length>0)throw new ControlUiGitHubError(502,`GitHub GraphQL request failed; check repository access`,{retryable:false})}if(!e.ok){if(e.status===403&&o&&isRecord(a)&&a.errors===void 0&&(a.message===`Resource not accessible by integration`||a.message===`Resource not accessible by personal access token`))throw new GitHubGraphQLUnavailableError(e.status);throw githubResponseError(e)}return a}async function withOptionalGitHubAuth(e,t){try{return await t(e)}catch(n){const r=n instanceof ControlUiGitHubError?n.statusCode:0;if(e&&[401,403,429].includes(r))try{return await t(void 0)}catch(e){if(n instanceof ControlUiGitHubError&&n.statusCode===429&&e instanceof ControlUiGitHubError&&e.statusCode===429&&(n.retryAfterMs??Infinity)<(e.retryAfterMs??Infinity))throw n;throw e}throw n}}async function readGitHubJsonResponse(e,t=GITHUB_JSON_MAX_BYTES){if(!e.ok){if(e.status===403&&!isGitHubRateLimitResponse(e)){let n;try{n=(await readGitHubJsonBody(e,t)).value}catch{}if(isRecord(n)&&typeof n.message===`string`&&/\b(?:secondary rate limit|abuse detection)\b/iu.test(n.message)){const t=githubResponseError(e,true);const n=responseRequestScopes.get(e);throw n?retainGitHubCooldown(n.fetchImpl,n.credentialScope,n.resource,e,t):t}}await discardResponse(e);throw githubResponseError(e)}return(await readGitHubJsonBody(e,t)).value}async function readGitHubJsonBody(e,t=GITHUB_JSON_MAX_BYTES){let n;try{n=await readBoundedResponse(e,t)}catch(e){if(e instanceof ControlUiGitHubError)throw e;throw new ControlUiGitHubError(502,`GitHub response could not be read`)}try{return{value:JSON.parse(n.toString(`utf8`)),bytes:n.byteLength}}catch{throw new ControlUiGitHubError(502,`GitHub response was not valid JSON`)}}const jsonCaches=/* @__PURE__ */ new WeakMap;const GITHUB_JSON_CACHE_BYTES=8388608;const GITHUB_JSON_CACHE_ENTRIES=128;async function fetchGitHubJsonPage(e,t,n,r={}){const{maxBytes:i=GITHUB_JSON_MAX_BYTES,apiBaseUrl:a=GITHUB_API_BASE_URL}=r;const o=jsonCaches.get(t)??{pages:/* @__PURE__ */ new Map,bytes:0};jsonCaches.set(t,o);const s=JSON.stringify([a,e,githubApiCredentialCacheScope(n),i]);const c=o.pages.get(s);const remove=e=>{const t=o.pages.get(e);if(t){o.bytes-=t.bytes;o.pages.delete(e)}};let l=false;try{const u=await fetchGitHubApi(e,t,n,async e=>{l=true;await r.beforeRedirect?.(e)},r.identity,c?.etag,r.signal,void 0,a);if(u.status===304&&c&&!l){const e=u.headers.get(`link`)??c.link;const t=e===c.link?c:Object.freeze({...c,link:e});if(o.pages.get(s)===c)o.pages.set(s,t);await discardResponse(u);return t}if(!u.ok)await readGitHubJsonResponse(u,i);const{value:d,bytes:f}=await readGitHubJsonBody(u,i);remove(s);const p={value:d,link:u.headers.get(`link`)};const m=u.headers.get(`etag`);if(m&&m.length<=1024&&!l&&f<=GITHUB_JSON_CACHE_BYTES&&!/\bno-store\b/iu.test(u.headers.get(`cache-control`)??``)){const e=[d];while(e.length>0){const t=e.pop();if(t!==null&&typeof t===`object`){for(const n of Object.values(t))e.push(n);Object.freeze(t)}}o.pages.set(s,Object.freeze({...p,etag:m,bytes:f}));o.bytes+=f;while(o.pages.size>GITHUB_JSON_CACHE_ENTRIES||o.bytes>GITHUB_JSON_CACHE_BYTES)remove(o.pages.keys().next().value)}return p}catch(e){remove(s);throw e}}function fetchGitHubJson(e,t,n,r,i=GITHUB_API_BASE_URL){return withOptionalGitHubAuth(n,async n=>(await fetchGitHubJsonPage(e,t,n,{maxBytes:r,apiBaseUrl:i})).value)}export{readGitHubJsonResponse as _,GITHUB_REQUEST_TIMEOUT_MS as a,resolveGitHubApiUrls as b,fetchGitHubApi as c,formatControlUiGitHubPreviewError as d,githubApiCredentialCacheScope as f,readGitHubGraphQLResponse as g,readBoundedResponse as h,GITHUB_GRAPHQL_URL as i,fetchGitHubJson as l,optionalNumber as m,GITHUB_API_BASE_URL as n,GitHubGraphQLUnavailableError as o,githubRestApiPath as p,GITHUB_API_ORIGIN as r,discardResponse as s,ControlUiGitHubError as t,fetchGitHubJsonPage as u,readOptionalGitHubString as v,withOptionalGitHubAuth as x,requiredString as y};