import { packetText, parseAllPackets } from "./pktline";
const SIDEBAND_DATA = 1;
/** Extracts `ok <ref>` results from a receive-pack response that may be wrapped in side-band packets. */
function successfulRefs(body: Uint8Array): Set<string> {
const ok = new Set<string>();
const collect = (packets: ReturnType<typeof parseAllPackets>) => {
for (const packet of packets) {
if (packet.kind !== "data") continue;
if (packet.data[0] === SIDEBAND_DATA) {
collect(parseAllPackets(packet.data.subarray(1)));
continue;
}
const line = packetText(packet);
if (line?.startsWith("ok ")) ok.add(line.slice(3).trim());
}
};
collect(parseAllPackets(body));
return ok;
}
/** Commands the report acknowledged with `ok`; a report without any `ok` line applied nothing we can trust (CI-P6). */
export function appliedCommands<T extends { ref: string }>(report: Uint8Array, commands: T[]): T[] {
const ok = successfulRefs(report);
return commands.filter((command) => ok.has(command.ref));
}