UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

906 lines (905 loc) • 36.1 kB
import { m as readNonBlankString } from "../../string-coerce-CCIiB4H7.mjs"; import { s as asFiniteNumber } from "../../number-coercion-D6u-4YD8.mjs"; import { l as isRecord } from "../../record-coerce-CVPuDqcc.mjs"; import { r as truncateUtf16Safe } from "../../utf16-slice-CuDyEXgS.mjs"; import { t as pruneMapToMaxSize } from "../../map-size-BBr20tbc.mjs"; import { o as racePromiseWithAbortSignal } from "../../src-BPmQBLJp.mjs"; import { t as createSubsystemLogger } from "../../subsystem-BHJiy01V.mjs"; import { t as createStaleWhileRevalidateCache } from "../../stale-while-revalidate-cache-BRZEfv_f.mjs"; import "../../string-coerce-runtime-BwAZZDf5.mjs"; import "../../time-runtime-DoAwjF0T.mjs"; import "../../diagnostic-runtime-By09gTPa.mjs"; import { c as parseGitHubReadTarget, l as parseGitHubTarget, o as parseGitHubLinkParams, r as githubTargetUrl } from "../../targets-CFNRMYXS.mjs"; import { n as quoteGitHubSearchKeywords, r as validGitHubSearchRepository, t as parseGitHubSearchParams } from "../../search-params-BqoVzC8t.mjs"; import { _ as readGitHubJsonResponse, a as GITHUB_REQUEST_TIMEOUT_MS, b as resolveGitHubApiUrls, c as fetchGitHubApi, d as formatControlUiGitHubPreviewError, f as githubApiCredentialCacheScope, g as readGitHubGraphQLResponse, h as readBoundedResponse, i as GITHUB_GRAPHQL_URL, l as fetchGitHubJson, m as optionalNumber, n as GITHUB_API_BASE_URL, o as GitHubGraphQLUnavailableError, p as githubRestApiPath, r as GITHUB_API_ORIGIN, s as discardResponse, t as ControlUiGitHubError, u as fetchGitHubJsonPage, v as readOptionalGitHubString, x as withOptionalGitHubAuth, y as requiredString } from "../../github-api-C6HIcRTo.mjs"; import { n as githubPreviewView, t as githubChangeMetadata } from "../../view-model-Bu-ryg_k.mjs"; //#region extensions/github/src/session-reader.ts var SessionGitHubAccessError = class extends ControlUiGitHubError { constructor(e) { super(404, e); } }; function assertSessionGitHubTarget(e, t) { t.assertSelected(); if (!t.token || e.owner.toLowerCase() !== t.repository.owner.toLowerCase() || e.repo.toLowerCase() !== t.repository.repo.toLowerCase()) throw new SessionGitHubAccessError("GitHub repository is outside the selected session"); } function sessionGitHubRepositoryUrl(e) { return `${e.apiBaseUrl}/repos/${encodeURIComponent(e.repository.owner)}/${encodeURIComponent(e.repository.repo)}`; } /** A rename/transfer needs a newly admitted session target, never credential forwarding. */ function rejectSessionGitHubRedirect() { throw new SessionGitHubAccessError("GitHub repository target changed; reopen the session link"); } function assertSessionRepositoryUrl(e, t) { if (e.toLowerCase() !== sessionGitHubRepositoryUrl(t).toLowerCase()) throw new SessionGitHubAccessError("GitHub response is outside the selected session"); } async function readSessionGitHubRepository(e, t, n) { const { value: r } = await fetchGitHubJsonPage(sessionGitHubRepositoryUrl(e), t, e.token, { beforeRedirect: rejectSessionGitHubRedirect, identity: e, signal: n, apiBaseUrl: e.apiBaseUrl }); if (!isRecord(r) || r.id !== e.repository.id || typeof r.full_name !== "string" || r.full_name.toLowerCase() !== `${e.repository.owner}/${e.repository.repo}`.toLowerCase()) throw new SessionGitHubAccessError("GitHub repository no longer matches the selected session"); return e.repository.id; } //#endregion //#region extensions/github/src/preview.ts const GITHUB_AVATAR_HOST = "avatars.githubusercontent.com"; const GITHUB_AVATAR_MAX_BYTES = 262144; const GITHUB_PREVIEW_TIMEOUT_MS = 2e3; const GITHUB_COMMITS_PAGE_SIZE = 100; const GITHUB_COMMITS_MAX_BYTES = 1048576; const CO_AUTHOR_FACE_LIMIT = 3; const CO_AUTHOR_TRAILER = /^co-authored-by:[^<\r\n\u2028\u2029]*<(?<id>\d{1,12})\+(?<login>[a-z\d](?:[a-z\d-]{0,38}))@users\.noreply\.github\.com>[^\S\r\n\u2028\u2029]*$/gimu; const SUCCESS_CACHE_MS$1 = 6e4; const DECORATION_CACHE_MS = 3e5; const FAILURE_CACHE_MS = 3e4; const CACHE_LIMIT$1 = 200; const log = createSubsystemLogger("github/preview"); const previewCaches = /* @__PURE__ */ new WeakMap(); const avatarCaches = /* @__PURE__ */ new WeakMap(); const parseControlUiGitHubPreviewTarget = parseGitHubTarget; function isPublicGitHubRepository(e) { return isRecord(e) && e.private === false && e.visibility === "public"; } async function assertPublicGitHubRepository(e, t, n, r, i) { const { value: a } = await fetchGitHubJsonPage(e, t, n, { identity: r, signal: i, apiBaseUrl: GITHUB_API_ORIGIN }); if (!isPublicGitHubRepository(a)) throw new ControlUiGitHubError(404, "GitHub repository is not public"); return a; } function redirectedRepositoryApiUrl(e, t, n = GITHUB_API_ORIGIN) { const r = githubRestApiPath(t, n).split("/").filter(Boolean); const i = e.kind === "commit" ? "commits" : e.kind === "pull" ? "pulls" : "issues"; const validId = (t) => e.kind === "commit" ? /^[a-f\d]{7,40}$/iu.test(t) : /^\d+$/u.test(t); const a = r.at(-1) === "commits" ? r.slice(0, -1) : r; if (a.length === 5 && a[0] === "repos" && a[1] && a[2] && a[3] === i && validId(a[4] ?? "")) return `${n}/repos/${a[1]}/${a[2]}`; if (a.length === 4 && a[0] === "repositories" && /^\d+$/u.test(a[1] ?? "") && a[2] === i && validId(a[3] ?? "")) return `${n}/repositories/${a[1]}`; return null; } function previewRepositoryApiUrl(e, t, n) { if (e.kind === "commit") { const r = redirectedRepositoryApiUrl(e, new URL(requiredString(t, "url")), n); if (!r) throw new ControlUiGitHubError(502, "GitHub commit returned an invalid repository"); return r; } if (e.kind === "issue") return requiredString(t, "repository_url"); const r = isRecord(t.base) ? t.base : {}; const i = isRecord(r.repo) ? r.repo : {}; return requiredString(i, "url"); } function parseControlUiGitHubPreviewResponse(e, t) { if (e.kind === "commit") { const n = requiredString(t, "sha"); if (!/^[a-f\d]{40}$/iu.test(n) || !n.toLowerCase().startsWith(e.sha)) throw new ControlUiGitHubError(502, "GitHub commit returned a different revision"); const r = isRecord(t.commit) ? t.commit : {}; const i = isRecord(t.author) ? t.author : {}; const a = isRecord(r.author) ? r.author : {}; const o = isRecord(t.stats) ? t.stats : {}; const s = requiredString(a, "date"); return { preview: { ...e, title: requiredString(r, "message").split("\n", 1)[0], login: readNonBlankString(i.login) ?? "ghost", createdAt: s, updatedAt: s, state: "committed", additions: asFiniteNumber(o.additions), deletions: asFiniteNumber(o.deletions), comments: asFiniteNumber(r.comment_count) }, avatarUrl: readNonBlankString(i.avatar_url) }; } const n = isRecord(t.user) ? t.user : {}; return { preview: { ...e, additions: asFiniteNumber(t.additions), changedFiles: asFiniteNumber(t.changed_files), closedAt: readNonBlankString(t.closed_at), comments: asFiniteNumber(t.comments), createdAt: requiredString(t, "created_at"), deletions: asFiniteNumber(t.deletions), draft: typeof t.draft === "boolean" ? t.draft : void 0, login: readNonBlankString(n.login) ?? "ghost", mergedAt: readNonBlankString(t.merged_at), state: requiredString(t, "state"), stateReason: readNonBlankString(t.state_reason), title: requiredString(t, "title"), updatedAt: requiredString(t, "updated_at") }, avatarUrl: readNonBlankString(n.avatar_url) }; } function safeAvatarUrl(e) { if (!e) return null; const t = URL.parse(e); const n = e.search(/[?#]/u); const r = n === -1 ? e : e.slice(0, n); if (!t || t.protocol !== "https:" || t.hostname !== GITHUB_AVATAR_HOST || t.hash || t.username || t.password || t.port || r.includes("..") || r.includes("\\") || t.pathname.includes("..") || t.pathname.includes("\\")) return null; t.search = ""; t.searchParams.set("s", "64"); return t; } async function fetchAvatarDataUrl(e, t, n) { const r = safeAvatarUrl(e); if (!r) return; try { let e = avatarCaches.get(t); if (!e) { e = createStaleWhileRevalidateCache({ maxEntries: CACHE_LIMIT$1, ttlMs: DECORATION_CACHE_MS, cacheable: (e) => e !== void 0 }); avatarCaches.set(t, e); } const { value: i } = await racePromiseWithAbortSignal(e.read(r.href, async () => { const e = await t(r, { headers: { Accept: "image/webp,image/png,image/jpeg,image/gif" }, redirect: "error", signal: AbortSignal.timeout(GITHUB_PREVIEW_TIMEOUT_MS) }); const n = e.headers.get("content-type")?.split(";", 1)[0]?.trim(); if (!e.ok || !n || ![ "image/gif", "image/jpeg", "image/png", "image/webp" ].includes(n)) { await discardResponse(e); return; } return `data:${n};base64,${(await readBoundedResponse(e, GITHUB_AVATAR_MAX_BYTES)).toString("base64")}`; }), n); return i; } catch { return; } } async function fetchPreview(e, t, n, r, i, a) { const o = a?.apiBaseUrl ?? "https://api.github.com"; const s = performance.now(); const assertRepository = (e) => { if (a) { assertSessionRepositoryUrl(e, a); return readSessionGitHubRepository(a, t, n); } return assertPublicGitHubRepository(e, t, r, i, n); }; const c = `${o}/repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`; const l = e.kind === "commit" ? "commits" : e.kind === "pull" ? "pulls" : "issues"; const u = e.kind === "commit" ? e.sha : e.number; const d = c + "/" + l + "/" + u + (e.kind === "commit" ? "?per_page=1" : ""); if (r) await assertRepository(c); const f = a ? rejectSessionGitHubRedirect : r ? async (t) => { const n = redirectedRepositoryApiUrl(e, t); if (!n) throw new ControlUiGitHubError(502, "GitHub item returned an unsafe redirect"); await assertRepository(n); } : void 0; const readItem = async (e, a) => { const { value: s } = await fetchGitHubJsonPage(e, t, r, { beforeRedirect: f, identity: i, signal: n, apiBaseUrl: o, maxBytes: a }); return s; }; const p = readItem(d); const m = e.kind === "pull" ? readItem(`${d}/commits?per_page=${GITHUB_COMMITS_PAGE_SIZE}`, GITHUB_COMMITS_MAX_BYTES).catch(() => void 0) : Promise.resolve(void 0); const h = await p; if (!isRecord(h)) throw new ControlUiGitHubError(502, "GitHub response was not an object"); const g = performance.now(); const { preview: _, avatarUrl: v } = parseControlUiGitHubPreviewResponse(e, h); const y = performance.now(); const [b, x] = await Promise.all([ fetchAvatarDataUrl(v, t, n), m.then(async (r) => { const i = e.kind === "commit" ? [h] : r; const a = _.login; const o = { coAuthors: [], coAuthorCount: 0 }; if (!Array.isArray(i)) return o; const s = /* @__PURE__ */ new Map(); for (const e of i) { const t = isRecord(e) && isRecord(e.commit) ? e.commit : void 0; const n = readNonBlankString(t?.message); if (!n) continue; for (const e of n.matchAll(CO_AUTHOR_TRAILER)) { const t = e.groups?.login; const n = e.groups?.id; if (!t || !n || t.toLowerCase() === a.toLowerCase()) continue; const r = t.toLowerCase(); if (!s.has(r)) s.set(r, { login: t, accountId: n }); } } const c = [...s.values()].slice(0, CO_AUTHOR_FACE_LIMIT); return { coAuthors: await Promise.all(c.map(async (e) => { const r = await fetchAvatarDataUrl(`https://${GITHUB_AVATAR_HOST}/u/${e.accountId}`, t, n); return r ? { login: e.login, avatarDataUrl: r } : { login: e.login }; })), coAuthorCount: s.size }; }), a ? assertSessionRepositoryUrl(previewRepositoryApiUrl(e, h, o), a) : r && assertRepository(previewRepositoryApiUrl(e, h, o)) ]); const S = performance.now(); if (S - s >= 500) log.info("Slow GitHub preview load", { metadataMs: Math.round(g - s), renderMs: Math.round(y - g), decorationMs: Math.round(S - y) }); return { ..._, ...b ? { avatarDataUrl: b } : {}, ...x.coAuthorCount > 0 ? { coAuthors: x.coAuthors, coAuthorCount: x.coAuthorCount } : {} }; } function cacheKey(e, t) { return `${e.kind}:${e.owner.toLowerCase()}/${e.repo.toLowerCase()}#${e.kind === "commit" ? e.sha : e.number}\0${t}`; } async function loadControlUiGitHubPreview(e, t, n = fetch, r = false) { const i = performance.now(); t?.assertSelected(); const { token: a, cacheScope: o } = t ?? { token: void 0, cacheScope: "anonymous" }; const s = cacheKey(e, `${o}\0${githubApiCredentialCacheScope(a)}`); const c = previewCaches.get(n) ?? createStaleWhileRevalidateCache({ maxEntries: CACHE_LIMIT$1, ttlMs: SUCCESS_CACHE_MS$1, errorTtlMs: (e) => e instanceof ControlUiGitHubError ? FAILURE_CACHE_MS : 0 }); previewCaches.set(n, c); const l = await c.read(s, () => { const r = AbortSignal.timeout(GITHUB_PREVIEW_TIMEOUT_MS); return t && !t.optionalAuth ? fetchPreview(e, n, r, a, t) : withOptionalGitHubAuth(a, (i) => fetchPreview(e, n, r, i, t)); }, { refresh: r }); const u = performance.now(); await t?.revalidate(); t?.assertSelected(); const d = performance.now(); if (d - i >= 500) log.info("Slow GitHub preview read", { cacheWaitMs: Math.round(u - i), deliveryAuthMs: Math.round(d - u), stale: l.stale, refresh: r }); return l.stale || t?.stale ? { ...l.value, stale: true } : l.value; } /** Foreground session reads finish inline; no background refresh outlives caller authority. */ async function loadSessionGitHubPreview(e, t, n = fetch) { assertSessionGitHubTarget(e, t); await t.revalidate(); const r = AbortSignal.timeout(GITHUB_PREVIEW_TIMEOUT_MS); const i = await fetchPreview(e, n, t.signal ? AbortSignal.any([r, t.signal]) : r, t.token, t, t); await t.revalidate(); t.assertSelected(); return i; } //#endregion //#region extensions/github/src/detail-checks.ts const CHECK_LIMIT = 100; const LABEL_MAX_CHARS = 256; const STATE_ORDER = { failure: 0, pending: 1, success: 2, neutral: 3 }; const RUN_STATES = /* @__PURE__ */ new Map([ ["queued", { state: "pending", detail: "Queued" }], ["in_progress", { state: "pending", detail: "In progress" }], ["waiting", { state: "pending", detail: "Waiting" }], ["requested", { state: "pending", detail: "Waiting" }], ["pending", { state: "pending", detail: "Waiting" }] ]); const RUN_CONCLUSIONS = /* @__PURE__ */ new Map([ ["success", { state: "success", detail: "Passed" }], ["neutral", { state: "neutral", detail: "Neutral" }], ["skipped", { state: "neutral", detail: "Skipped" }], ["failure", { state: "failure", detail: "Failed" }], ["cancelled", { state: "failure", detail: "Canceled" }], ["timed_out", { state: "failure", detail: "Timed out" }], ["action_required", { state: "failure", detail: "Action required" }], ["stale", { state: "failure", detail: "Stale" }], ["startup_failure", { state: "failure", detail: "Could not start" }] ]); const STATUS_STATES = /* @__PURE__ */ new Map([ ["success", { state: "success", detail: "Passed" }], ["pending", { state: "pending", detail: "Pending" }], ["failure", { state: "failure", detail: "Failed" }], ["error", { state: "failure", detail: "Error" }] ]); function count(e) { if (typeof e !== "number" || !Number.isSafeInteger(e) || e < 0) throw new ControlUiGitHubError(502, "GitHub checks returned an invalid count"); return e; } function checkUrl(e) { if (typeof e !== "string" || e.length > 4096) return; const t = URL.parse(e); return t?.protocol === "https:" && !t.username && !t.password ? t.href : void 0; } function checkState(e, t) { const n = t === "statuses" ? STATUS_STATES.get(e.state) : e.status === "completed" ? RUN_CONCLUSIONS.get(e.conclusion) : RUN_STATES.get(e.status); if (!n) throw new ControlUiGitHubError(502, t === "runs" ? "GitHub check returned an unknown state" : "GitHub commit status returned an unknown state"); return n; } function parsePage(e, t, n) { if (!isRecord(e.value)) throw new ControlUiGitHubError(502, "GitHub checks were not an object"); const r = e.value; const i = n === "runs" ? r.check_runs : r.statuses; if (!Array.isArray(i) || n === "statuses" && r.sha !== t) throw new ControlUiGitHubError(502, "GitHub checks returned a different revision or invalid list"); const a = count(r.total_count); const o = /* @__PURE__ */ new Map(); for (const e of i.slice(0, CHECK_LIMIT)) { if (!isRecord(e) || n === "runs" && e.head_sha !== t) throw new ControlUiGitHubError(502, "GitHub check returned a different revision or invalid item"); const r = count(e.id); const i = requiredString(e, n === "runs" ? "name" : "context"); const a = n === "runs" ? String(r) : i.toLowerCase(); if ((o.get(a)?.id ?? -1) >= r) continue; o.set(a, { id: r, item: { name: i.slice(0, LABEL_MAX_CHARS), ...checkState(e, n), url: checkUrl(n === "runs" ? e.html_url : e.target_url) } }); } const s = Math.max(0, a - Math.min(i.length, CHECK_LIMIT)); return { items: Array.from(o.values(), ({ item: e }) => e), total: o.size + s, truncated: e.hasNextPage || s > 0 || i.length > CHECK_LIMIT }; } async function fetchPullChecks(e, t, n, r) { if (typeof t !== "string" || !/^[a-f0-9]{40}$/u.test(t)) return { state: "unavailable", summary: "Checks unavailable", total: 0, items: [], truncated: true, url: n }; const i = e + "/commits/" + t; const a = []; let o = 0; let s = false; for (const e of ["runs", "statuses"]) try { const n = parsePage(await r(i + (e === "runs" ? "/check-runs?filter=latest&per_page=" : "/status?per_page=") + CHECK_LIMIT), t, e); a.push(...n.items); o += n.total; s ||= n.truncated; } catch { s = true; } a.sort((e, t) => STATE_ORDER[e.state] - STATE_ORDER[t.state] || e.name.localeCompare(t.name)); s ||= a.length > CHECK_LIMIT; const c = { success: 0, failure: 0, pending: 0, neutral: 0 }; for (const e of a) c[e.state] += 1; return { state: c.failure ? "failure" : c.pending ? "pending" : s ? "unavailable" : c.success ? "success" : "neutral", summary: [ s ? a.length ? "Checks incomplete" : "Checks unavailable" : void 0, c.failure ? c.failure + " failed" : void 0, c.pending ? c.pending + " pending" : void 0, c.success ? c.success + " passed" : void 0, c.neutral ? c.neutral + " skipped or neutral" : void 0 ].filter(Boolean).join(" · ") || "No checks reported", total: o, items: a.slice(0, CHECK_LIMIT), truncated: s, url: n, commit: t }; } //#endregion //#region extensions/github/src/detail.ts const DETAIL_JSON_MAX_BYTES = 1048576; const BODY_MAX_CHARS = 32768; const COMMENT_LIMIT = 20; const COMMENT_MAX_CHARS = 4096; const FILE_LIMIT = 30; const PATCH_MAX_CHARS = 16384; const PATCH_TOTAL_MAX_CHARS = 98304; const SUCCESS_CACHE_MS = 3e5; const PARTIAL_CACHE_MS = 3e4; const CACHE_LIMIT = 32; const detailCache = /* @__PURE__ */ new Map(); var GitHubDetailAccessError = class extends ControlUiGitHubError { constructor() { super(404, "GitHub repository is not public or has changed"); } }; function redirectedRepositoryUrl(e, t) { const n = /^(\/repos\/[^/]+\/[^/]+|\/repositories\/\d+)(\/.*)?$/u.exec(githubRestApiPath(e, GITHUB_API_ORIGIN)); if (!n || (n[2] ?? "") !== t) throw new GitHubDetailAccessError(); return GITHUB_API_ORIGIN + n[1]; } async function readPublicRepository(e, t, n, r) { const { value: i } = await fetchGitHubJsonPage(e, t, n?.token, { beforeRedirect: async (e) => { redirectedRepositoryUrl(e, ""); }, identity: n, apiBaseUrl: GITHUB_API_ORIGIN }); const a = isRecord(i) ? optionalNumber(i, "id") : void 0; if (!isPublicGitHubRepository(i) || a === void 0 || !Number.isSafeInteger(a) || a <= 0 || r !== void 0 && a !== r) throw new GitHubDetailAccessError(); return a; } function markdownBody(e, t) { const n = typeof e === "string" ? e : ""; return { body: truncateUtf16Safe(n, t), bodyTruncated: n.length > t }; } function requiredCount(e, t) { const n = optionalNumber(e, t); if (n === void 0 || !Number.isSafeInteger(n) || n < 0) throw new ControlUiGitHubError(502, `GitHub response omitted ${t}`); return n; } function commentPosition(e) { return typeof e === "number" && Number.isSafeInteger(e) && e > 0 ? e : void 0; } function commentUrl(e, t) { const n = new URL(requiredString(e, "html_url")); if (n.origin !== `https://${t}` || n.username || n.password) throw new ControlUiGitHubError(502, "GitHub comment returned an unsafe permalink"); return n.href; } function parseComments(e, t, n) { if (!Array.isArray(e)) throw new ControlUiGitHubError(502, "GitHub comments were not an array"); return e.slice(0, COMMENT_LIMIT).map((e) => { if (!isRecord(e)) throw new ControlUiGitHubError(502, "GitHub comment was not an object"); const r = isRecord(e.user) ? e.user : {}; const { body: i, bodyTruncated: a } = markdownBody(e.body, COMMENT_MAX_CHARS); const o = t === "review" ? markdownBody(e.diff_hunk, COMMENT_MAX_CHARS) : void 0; const s = requiredCount(e, "id"); const c = commentUrl(e, n); const l = t !== "discussion" ? readOptionalGitHubString(e, "path") : void 0; const u = commentPosition(e.line) ?? commentPosition(e.original_line); const d = commentPosition(e.start_line) ?? commentPosition(e.original_start_line); const f = u === void 0 ? void 0 : (d !== void 0 && d !== u ? d + "–" : "") + u; const p = t === "review" ? commentPosition(e.in_reply_to_id) : void 0; const m = [e.side === "LEFT" ? "Before change" : e.side === "RIGHT" ? "After change" : void 0, e.line == null && commentPosition(e.original_line) ? "Outdated" : void 0].filter(Boolean); return { id: new URL(c).hash.slice(1) || (t === "review" ? "discussion_r" : t === "commit" ? "commitcomment-" : "issuecomment-") + s, url: c, author: readOptionalGitHubString(r, "login") ?? "ghost", createdAt: requiredString(e, "created_at"), body: i, bodyTruncated: a, label: t === "review" ? "Review comment" : void 0, context: t !== "discussion" ? { path: l, lineLabel: f, label: m.join(" · ") || void 0, diff: o?.body, diffTruncated: t === "review" ? typeof e.diff_hunk !== "string" || o?.bodyTruncated : void 0, replyUrl: p === void 0 ? void 0 : new URL("#discussion_r" + p, c).href, replyLabel: p === void 0 ? void 0 : "In reply to #" + p } : void 0 }; }); } async function fetchComments(e, t, n, r, i) { if (n === 0) return { comments: [], commentsTotal: 0, commentsTruncated: false }; try { const a = t === "review" ? "&sort=created&direction=asc" : ""; const o = await r(e + "?per_page=20" + a); const s = parseComments(o.value, t, i); return { comments: s, commentsTotal: n, commentsTruncated: o.hasNextPage || n > s.length || Array.isArray(o.value) && o.value.length > COMMENT_LIMIT }; } catch (e) { if (e instanceof GitHubDetailAccessError || e instanceof SessionGitHubAccessError) throw e; return { comments: [], commentsTotal: n, commentsTruncated: true }; } } function parseFiles(e) { if (!Array.isArray(e)) throw new ControlUiGitHubError(502, "GitHub files were not an array"); let t = PATCH_TOTAL_MAX_CHARS; return e.slice(0, FILE_LIMIT).map((e) => { if (!isRecord(e)) throw new ControlUiGitHubError(502, "GitHub file was not an object"); const n = typeof e.patch === "string" ? e.patch : void 0; const r = n === void 0 ? void 0 : truncateUtf16Safe(n, Math.min(PATCH_MAX_CHARS, t)); t -= r?.length ?? 0; return { path: requiredString(e, "filename"), previousPath: readOptionalGitHubString(e, "previous_filename"), status: requiredString(e, "status"), additions: requiredCount(e, "additions"), deletions: requiredCount(e, "deletions"), patch: r, patchTruncated: n === void 0 || r?.length !== n.length }; }); } async function loadGitHubDetailWithIdentity(e, t, n = fetch, r = false, i, a) { const o = i?.apiBaseUrl ?? "https://api.github.com"; const s = parseGitHubTarget(e); if (!s) throw new ControlUiGitHubError(400, "Invalid GitHub detail target"); await t?.revalidate(); t?.assertSelected(); const c = s.kind === "commit" ? s.sha : s.number; const l = `${o}\0${s.kind}:${s.owner.toLowerCase()}/${s.repo.toLowerCase()}#${c}\0${t?.cacheScope ?? "anonymous"}\0${githubApiCredentialCacheScope(t?.token)}\0`; const u = l + (a ?? "complete"); const assertDelivery = async (e) => { if (t?.token && !i) for (const r of e.repositoryUrls) await readPublicRepository(r, n, t, e.repositoryId); await t?.revalidate(); t?.assertSelected(); }; const d = detailCache.get(u); if (!r && d && d.expiresAt > Date.now() && (!t || d.settled)) { detailCache.delete(u); detailCache.set(u, d); const e = await d.promise; await assertDelivery(e); return e.document; } if (r || a === "overview") { for (const e of detailCache.keys()) if (e.startsWith(l)) detailCache.delete(e); } detailCache.delete(u); const f = s.kind !== "issue" && a && a !== "overview" && a !== "files" && !r ? detailCache.get(l + "overview") : void 0; const p = f?.settled && f.expiresAt > Date.now() ? await f.promise : void 0; const load = async () => { const e = `${o}/repos/${encodeURIComponent(s.owner)}/${encodeURIComponent(s.repo)}`; const r = /* @__PURE__ */ new Set([e, ...p?.repositoryUrls ?? []]); const l = i ? await readSessionGitHubRepository(i, n) : t?.token ? await readPublicRepository(e, n, t, p?.repositoryId) : void 0; if (!t?.token) await assertPublicGitHubRepository(e, n, void 0, t); const readPage = async (a) => { const s = new URL(a).pathname.slice(new URL(e).pathname.length); const c = await fetchGitHubJsonPage(a, n, t?.token, { beforeRedirect: i ? rejectSessionGitHubRedirect : t?.token ? async (e) => { const i = redirectedRepositoryUrl(e, s); await readPublicRepository(i, n, t, l); r.add(i); } : void 0, identity: t, apiBaseUrl: o, maxBytes: DETAIL_JSON_MAX_BYTES }); return { hasNextPage: /;\s*rel="next"/u.test(c.link ?? ""), value: c.value }; }; const u = s.kind === "commit" ? "commits" : s.kind === "pull" ? "pulls" : "issues"; const d = e + "/" + u + "/" + c; const f = p?.itemPage ?? await readPage(s.kind === "commit" ? d + "?per_page=30" : d); const m = i?.host ?? "github.com"; const fetchDetail = async () => { if (!isRecord(f.value)) throw new ControlUiGitHubError(502, "GitHub response was not an object"); const t = f.value; const n = githubTargetUrl(s, m); const r = a === void 0 || a === "discussion"; const i = a === void 0 || a === "files"; const o = a === void 0 || a === "checks"; const c = s.kind === "pull" ? [ "checks", "files", "discussion" ] : s.kind === "commit" ? ["files", "discussion"] : ["discussion"]; if (s.kind === "commit") { const e = isRecord(t.commit) ? t.commit : {}; const o = isRecord(t.author) ? t.author : {}; const l = isRecord(e.author) ? e.author : {}; const u = isRecord(t.stats) ? t.stats : {}; const p = markdownBody(e.message, BODY_MAX_CHARS); const h = r ? await fetchComments(d + "/comments", "commit", requiredCount(e, "comment_count"), readPage, m) : void 0; const g = !i || t.files === void 0 ? [] : parseFiles(t.files); const _ = t.files === void 0 || f.hasNextPage || Array.isArray(t.files) && t.files.length > FILE_LIMIT; return { url: n, revision: requiredString(t, "sha"), ...a === "overview" ? { deferredSections: c } : {}, subtitle: s.owner + "/" + s.repo + " · " + requiredString(t, "sha").slice(0, 12), badge: { label: "Commit", tone: "neutral" }, title: p.body.split("\n", 1)[0] ?? "", author: readOptionalGitHubString(o, "login") ?? readOptionalGitHubString(l, "name") ?? "ghost", createdAt: readOptionalGitHubString(l, "date"), metadata: githubChangeMetadata(optionalNumber(u, "additions"), optionalNumber(u, "deletions")), ...p, ...h, ...i ? { files: g, filesTruncated: _ } : {}, partial: p.bodyTruncated || h?.commentsTruncated === true || i && _ || h?.comments.some((e) => e.bodyTruncated) === true || g.some((e) => e.patchTruncated) }; } const { preview: l } = parseControlUiGitHubPreviewResponse(s, t); const u = markdownBody(t.body, BODY_MAX_CHARS); const p = r ? requiredCount(t, "comments") : 0; const h = r && s.kind === "pull" ? requiredCount(t, "review_comments") : 0; const [g, _] = r ? await Promise.all([fetchComments(e + "/issues/" + s.number + "/comments", "discussion", p, readPage, m), s.kind === "pull" ? fetchComments(d + "/comments", "review", h, readPage, m) : void 0]) : []; const v = (g?.comments ?? []).concat(_?.comments ?? []).toSorted((e, t) => (e.createdAt ?? "").localeCompare(t.createdAt ?? "") || e.id.localeCompare(t.id, "en", { numeric: true })); const y = (g?.commentsTotal ?? 0) + (_?.commentsTotal ?? 0); const b = g?.commentsTruncated === true || _?.commentsTruncated === true; let x = []; let S = false; const C = s.kind === "pull" ? requiredCount(t, "changed_files") : 0; if (i && C > 0) try { const e = await readPage(`${d}/files?per_page=${FILE_LIMIT}`); x = parseFiles(e.value); S = e.hasNextPage || C > x.length; } catch (e) { if (e instanceof GitHubDetailAccessError || e instanceof SessionGitHubAccessError) throw e; S = true; } const w = isRecord(t.head) ? t.head : {}; const T = isRecord(t.base) ? t.base : {}; const E = s.kind === "pull" && o ? await fetchPullChecks(e, w.sha, n + "/checks", readPage) : void 0; const D = githubPreviewView(l, m); const O = githubChangeMetadata(l.additions, l.deletions, l.changedFiles, l.comments); const k = readOptionalGitHubString(w, "ref")?.slice(0, 256); const A = readOptionalGitHubString(T, "ref")?.slice(0, 256); return { ...D, metadata: s.kind === "pull" && k && A ? [...O, { label: "Branch", value: k + " → " + A }] : O, url: n, revision: s.kind === "pull" ? readOptionalGitHubString(w, "sha") : l.updatedAt, ...a === "overview" ? { deferredSections: c } : {}, ...u, ...E ? { checks: E } : {}, ...r ? { comments: v, commentsTotal: y, commentsTruncated: b } : {}, ...i ? { files: x, filesTotal: C, filesTruncated: S } : {}, partial: u.bodyTruncated || b || S || E?.truncated === true || E?.state === "unavailable" || v.some((e) => e.bodyTruncated || e.context?.diffTruncated) || x.some((e) => e.patchTruncated) }; }; const h = await fetchDetail(); if (a === "files" && s.kind === "pull") { const e = (await readPage(d)).value; if (!isRecord(e) || !isRecord(e.head) || !h.revision || e.head.sha !== h.revision) throw new ControlUiGitHubError(409, "GitHub pull request changed; refresh the reader"); } const g = { document: h, itemPage: f, repositoryId: l, repositoryUrls: [...r] }; await assertDelivery(g); return g; }; const m = { expiresAt: Date.now() + SUCCESS_CACHE_MS, settled: false, promise: load().then((e) => { m.settled = true; if (s.kind === "pull" || e.document.partial) m.expiresAt = Date.now() + PARTIAL_CACHE_MS; return e; }).catch((e) => { if (e instanceof ControlUiGitHubError && e.statusCode !== 409) { m.settled = true; m.expiresAt = Date.now() + PARTIAL_CACHE_MS; } else if (detailCache.get(u) === m) detailCache.delete(u); throw e; }) }; detailCache.set(u, m); pruneMapToMaxSize(detailCache, CACHE_LIMIT); const h = await m.promise; t?.assertSelected(); return h.document; } function loadGitHubDetail(e, t, n = fetch, r = false, i) { if (e.kind === "job") { const load = async (t) => { const { loadGitHubJobLog: r } = await import("../../job-logs-BVubFS1o.mjs"); return r(e, t, n, async (r) => readPublicRepository(`${GITHUB_API_ORIGIN}/repos/${encodeURIComponent(e.owner)}/${encodeURIComponent(e.repo)}`, n, t, r)); }; return t?.optionalAuth ? withOptionalGitHubAuth(t.token, (e) => load({ ...t, token: e })) : load(t); } return t?.optionalAuth ? withOptionalGitHubAuth(t.token, (a) => loadGitHubDetailWithIdentity(e, { ...t, token: a }, n, r, void 0, i)) : loadGitHubDetailWithIdentity(e, t, n, r, void 0, i); } function loadSessionGitHubDetail(e, t, n = fetch, r = false, i) { assertSessionGitHubTarget(e, t); return loadGitHubDetailWithIdentity(e, t, n, r, t, i); } //#endregion //#region extensions/github/src/search.ts const PAGE_SIZE = 20; const RESULT_LIMIT = 1e3; async function searchWithIdentity(e, t, n) { const r = `${GITHUB_API_ORIGIN}/repos/${e.repository}`; const i = await assertPublicGitHubRepository(r, n, t?.token, t); const a = requiredString(i, "full_name"); if (!validGitHubSearchRepository(a) || typeof i.id !== "number" || !Number.isSafeInteger(i.id) || i.id < 1) throw new ControlUiGitHubError(502, "GitHub returned invalid repository metadata"); const o = quoteGitHubSearchKeywords(e.query); const s = [ `repo:${a}`, "is:public", `is:${e.kind === "pull" ? "pull-request" : "issue"}`, ...e.state === "all" ? [] : [`is:${e.state}`], ...o ? [o] : [] ].join(" "); const c = new URL(`${GITHUB_API_ORIGIN}/search/issues`); c.search = new URLSearchParams({ q: s, sort: "updated", order: "desc", per_page: String(PAGE_SIZE), page: String(e.page) }).toString(); const { value: l } = await fetchGitHubJsonPage(c.href, n, t?.token, { beforeRedirect: async () => { throw new ControlUiGitHubError(502, "GitHub search returned an unexpected redirect"); }, identity: t, apiBaseUrl: GITHUB_API_ORIGIN, maxBytes: 1048576 }); if (!isRecord(l) || typeof l.total_count !== "number" || !Number.isSafeInteger(l.total_count) || l.total_count < 0 || typeof l.incomplete_results !== "boolean" || !Array.isArray(l.items) || l.items.length > PAGE_SIZE) throw new ControlUiGitHubError(502, "GitHub returned an invalid search page"); const u = l.items.map((t) => { const n = isRecord(t) ? parseGitHubLinkParams({ url: t.html_url }) : null; if (!isRecord(t) || !n || n.target.kind === "commit" || `${n.target.owner}/${n.target.repo}`.toLowerCase() !== a.toLowerCase() || typeof t.repository_url !== "string" || t.repository_url.toLowerCase() !== `${"https://api.github.com"}/repos/${a}`.toLowerCase() || t.number !== n.target.number || (t.pull_request ? "pull" : "issue") !== n.target.kind || n.target.kind !== e.kind || t.state !== "open" && t.state !== "closed" || e.state !== "all" && t.state !== e.state) throw new ControlUiGitHubError(502, "GitHub search returned an item outside the requested scope"); return { url: n.url, number: n.target.number, kind: n.target.kind, title: truncateUtf16Safe(requiredString(t, "title"), 512), state: t.state, updatedAt: requiredString(t, "updated_at") }; }); if ((await assertPublicGitHubRepository(`${"https://api.github.com"}/repos/${a}`, n, t?.token, t)).id !== i.id) throw new ControlUiGitHubError(404, "GitHub repository is not public or has changed"); await t?.revalidate(); t?.assertSelected(); return { repository: a, kind: e.kind, page: e.page, pageSize: PAGE_SIZE, totalCount: l.total_count, incomplete: l.incomplete_results, resultLimit: RESULT_LIMIT, limited: l.total_count > RESULT_LIMIT, nextPage: e.page * PAGE_SIZE < Math.min(l.total_count, RESULT_LIMIT) ? e.page + 1 : null, items: u }; } function searchPublicGitHubItems(e, t, n = fetch) { return t?.optionalAuth ? withOptionalGitHubAuth(t.token, (r) => searchWithIdentity(e, { ...t, token: r }, n)) : searchWithIdentity(e, t, n); } //#endregion export { ControlUiGitHubError, GITHUB_API_BASE_URL, GITHUB_API_ORIGIN, GITHUB_GRAPHQL_URL, GITHUB_REQUEST_TIMEOUT_MS, GitHubGraphQLUnavailableError, discardResponse, fetchGitHubApi, fetchGitHubJson, fetchGitHubJsonPage, formatControlUiGitHubPreviewError, githubApiCredentialCacheScope, isRecord, loadControlUiGitHubPreview, loadGitHubDetail, loadSessionGitHubDetail, loadSessionGitHubPreview, optionalNumber, parseControlUiGitHubPreviewTarget, parseGitHubReadTarget, parseGitHubSearchParams, parseGitHubTarget, readBoundedResponse, readGitHubGraphQLResponse, readGitHubJsonResponse, readOptionalGitHubString, requiredString, resolveGitHubApiUrls, searchPublicGitHubItems, withOptionalGitHubAuth };