import { AsyncLocalStorage } from "node:async_hooks";
import { env } from "cloudflare:workers";
import { parsePack } from "../../git/pack";
import type { ParsedPack } from "../../git/pack";
import { concatBytes, FLUSH_PKT, packetText, parseAllPackets, pktLine } from "../../git/pktline";
import { limitStream, PackTooLargeError } from "../../git/ref-sync-protocol";
import { packFromResponse } from "../../git/snapshot";
import { guardedFetch } from "../../git/relay";
/**
* Git smart-HTTP (protocol v2) against github.com, for resolving and downloading actions. Going through git
* rather than the REST API or codeload tarballs matters twice: anonymous REST calls from shared egress IPs
* hit GitHub's 60/hour limit at once, and git objects are content-addressed, so every downloaded object can
* be checked against the SHA it is named by (a tarball can't be tied back to a commit).
*/
const ORIGIN = "https://github.com";
const DELIM_PKT = new TextEncoder().encode("0001");
const USER_AGENT = "git/gitfor-actions";
/** api.github.com answers an HTML 403 to authenticated requests whose User-Agent starts with `git/`. */
const API_USER_AGENT = "gitfor-actions";
/** GitHub answers 401 (not 404) for a repository that is private or doesn't exist. */
const MISSING_STATUSES = new Set([401, 403, 404]);
const LS_REFS_TIMEOUT_MS = 20_000;
const FETCH_TIMEOUT_MS = 60_000;
const MAX_REF_BYTES = 8 * 1024 * 1024;
const MAX_REACHABILITY_PACK_BYTES = 12 * 1024 * 1024;
const MAX_REACHABILITY_TIPS = 200;
const PARENT_LINE = /^parent ([0-9a-f]{40,64})$/gm;
const decoder = new TextDecoder();
/**
* Isolates have 128 MB, and the pack, its inflated objects, the tar and its gzip are all alive together while an
* archive is built, so the budgets stay well under a quarter of that each. Most JavaScript actions are a few MB.
*/
export const MAX_ACTION_PACK_BYTES = 16 * 1024 * 1024;
const ACTION_PACK_LIMITS = { maxObjects: 40_000, maxObjectBytes: 16 * 1024 * 1024, maxTotalBytes: 24 * 1024 * 1024 };
export class ActionSourceError extends Error {}
/** GitHub refused for now (rate limit or outage), as opposed to the action not existing. */