Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/exports.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,23 @@ export interface ExportPage {
nextCursor: string | null;
}

/** Splits an already decoded CSV page without treating quoted newlines as record boundaries. */
export const splitCsvHeader = (
text: string,
): { header: string; body: string } => {
let quoted = false;
for (let index = 0; index < text.length; index += 1) {
const character = text[index];
if (character === '"') quoted = !quoted;
if (!quoted && (character === "\r" || character === "\n")) {
const end =
index + (character === "\r" && text[index + 1] === "\n" ? 2 : 1);
return { header: text.slice(0, index), body: text.slice(end) };
}
}
return { header: text, body: "" };
};

// Version 2 of the finding datasets adds code-lane rows. Version 1 stays accepted from servers
// that have not moved to version 2.
const versions: Record<string, readonly string[]> = {
Expand Down
39 changes: 39 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
decodeExport,
type ExportPage,
type ExportParameters,
splitCsvHeader,
} from "./exports.js";

export type { ExportPage, ExportParameters } from "./exports.js";
Expand Down Expand Up @@ -151,6 +152,44 @@ export class ProoflineClient extends Operations {
throw paginationLimit("the export continues past maxPages");
}

/**
* Yields CSV or NDJSON text for one output stream, retaining the original cells
* and one CSV header. Each nonempty chunk ends at a record boundary. CSV
* headers must match the first page, excluding their line ending.
*
* Pass the iterator to `Readable.from` and `pipeline` to write an export with
* backpressure. Pages are read on demand; pagination bounds and failures from
* `iterExportPages` propagate, so a partial export is never reported complete.
*/
async *iterExportChunks(
parameters: ExportParameters,
options: { maxPages?: number } = {},
): AsyncGenerator<string> {
let header: string | undefined;
for await (const page of this.iterExportPages(parameters, options)) {
let text = page.text;
if (!text) continue;
if (page.format === "csv") {
const csv = splitCsvHeader(text);
if (header === undefined) header = csv.header;
else {
if (csv.header !== header)
throw new ProoflineError(
0,
"urn:proofline:sdk:invalid-response",
"the CSV export header changed between pages",
);
text = csv.body;
}
}
if (text) {
const terminated =
text.endsWith("\n") || (page.format === "csv" && text.endsWith("\r"));
yield terminated ? text : `${text}\n`;
}
}
}

/** Reads coverage reports from disk and uploads them in one request. */
async uploadCoverageFiles(
parameters: UploadCoverageReportsParameters,
Expand Down
165 changes: 165 additions & 0 deletions tests/http.test.mjs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { once } from "node:events";
import { createWriteStream } from "node:fs";
import {
cp,
mkdtemp,
Expand All @@ -13,6 +14,8 @@ import {
import { createServer } from "node:http";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
import test from "node:test";
import { fileURLToPath, pathToFileURL } from "node:url";
import { inspect } from "node:util";
Expand Down Expand Up @@ -1878,6 +1881,168 @@ test("export pages follow cursors with the first call's filters, refusing cycles
assert.equal(bounded.length, 2);
});

test("export chunks pipe one CSV header and original quoted records to a file", async (t) => {
const header = 'dataset_version,"claim\nlabel",details';
const first = '1,"comma, quote "" and\nnewline","{""nested"":true}"';
const second = '1,"next\r\nrecord",last\r\n';
const pages = [
`${header}\r\n`,
`${header}\r\n${first}`,
`${header}\n${second}`,
];
const { baseUrl, calls } = await server(t, (_request, response, seen) => {
const index = seen.length - 1;
response.writeHead(200, {
"content-type": "text/csv",
"x-proofline-export-version": "1",
"x-proofline-export-settled-until": "2026-10-25T00:00:00Z",
...(index < 2
? { "x-proofline-export-next-cursor": `page-${index + 2}` }
: {}),
});
response.end(pages[index]);
});
const work = await mkdtemp(join(tmpdir(), "sdk-export-stream-"));
t.after(() => rm(work, { recursive: true, force: true }));
const file = join(work, "reviews.csv");
const client = new ProoflineClient({ baseUrl, token });
await pipeline(
Readable.from(
client.iterExportChunks({
path: { org_id: orgId, dataset: "reviews" },
query: {
from: "2026-10-01T00:00:00Z",
to: "2026-10-25T00:00:00Z",
format: "csv",
},
}),
),
createWriteStream(file),
);
assert.equal(
await readFile(file, "utf8"),
`${header}\r\n${first}\n${second}`,
);
assert.equal(calls.length, 3);
});

test("export chunks separate NDJSON pages and fetch only when consumed", async (t) => {
const bodies = [
'{"dataset_version":1,"nested":{"text":"first"}}',
"",
'{"dataset_version":1,"text":"last"}\n',
];
const { baseUrl, calls } = await server(t, (_request, response, seen) => {
const index = seen.length - 1;
response.writeHead(200, {
"content-type": "application/x-ndjson",
"x-proofline-export-version": "1",
"x-proofline-export-settled-until": "2026-10-25T00:00:00Z",
...(index < 2
? { "x-proofline-export-next-cursor": `page-${index + 2}` }
: {}),
});
response.end(bodies[index]);
});
const client = new ProoflineClient({ baseUrl, token });
const parameters = {
path: { org_id: orgId, dataset: "reviews" },
query: {
from: "2026-10-01T00:00:00Z",
to: "2026-10-25T00:00:00Z",
group_by: "repository",
},
};
const chunks = client.iterExportChunks(parameters);
assert.equal(calls.length, 0);
assert.deepEqual(await chunks.next(), {
done: false,
value: `${bodies[0]}\n`,
});
assert.equal(calls.length, 1);
parameters.path.org_id = "another-organization";
parameters.query.from = "2026-10-20T00:00:00Z";
assert.deepEqual(await chunks.next(), { done: false, value: bodies[2] });
assert.equal(calls.length, 3);
assert.deepEqual(await chunks.next(), { done: true, value: undefined });
const sent = new URL(calls[2].url, baseUrl);
assert.match(sent.pathname, new RegExp(`/organizations/${orgId}/`));
assert.equal(sent.searchParams.get("from"), "2026-10-01T00:00:00Z");
assert.equal(sent.searchParams.get("group_by"), "repository");
});

test("stopping export chunks does not request another page", async (t) => {
const { baseUrl, calls } = await server(t, (_request, response) => {
response.writeHead(200, {
"content-type": "application/x-ndjson",
"x-proofline-export-version": "1",
"x-proofline-export-settled-until": "2026-10-25T00:00:00Z",
"x-proofline-export-next-cursor": "next",
});
response.end('{"dataset_version":1}\n');
});
const client = new ProoflineClient({ baseUrl, token });
for await (const _ of client.iterExportChunks({
path: { org_id: orgId, dataset: "reviews" },
query: { from: "2026-10-01T00:00:00Z", to: "2026-10-25T00:00:00Z" },
}))
break;
assert.equal(calls.length, 1);
});

test("export chunks refuse changed CSV headers and preserve pagination and HTTP errors", async (t) => {
for (const mode of ["header", "cycle", "limit", "http"]) {
await t.test(mode, async (t) => {
const { baseUrl, calls } = await server(t, (_request, response, seen) => {
const second = seen.length === 2;
if (second && mode === "http")
return json(response, 403, { detail: "not authorized" });
response.writeHead(200, {
"content-type": "text/csv",
"x-proofline-export-version": "1",
"x-proofline-export-settled-until": "2026-10-25T00:00:00Z",
...(!second || mode === "cycle"
? { "x-proofline-export-next-cursor": "next" }
: {}),
});
response.end(
`dataset_version,${second && mode === "header" ? "different" : "claim"}\n1,example\n`,
);
});
const client = new ProoflineClient({ baseUrl, token });
const chunks = client.iterExportChunks(
{
path: { org_id: orgId, dataset: "reviews" },
query: {
from: "2026-10-01T00:00:00Z",
to: "2026-10-25T00:00:00Z",
format: "csv",
},
},
{ maxPages: mode === "limit" ? 1 : 100 },
);
assert.equal(
(await chunks.next()).value,
"dataset_version,claim\n1,example\n",
);
const expected = {
header: "invalid-response",
cycle: "invalid-pagination",
limit: "pagination-limit",
}[mode];
await assert.rejects(
chunks.next(),
(error) =>
error instanceof ProoflineError &&
(mode === "http"
? error.status === 403
: error.type === `urn:proofline:sdk:${expected}`),
);
assert.equal(calls.length, mode === "limit" ? 1 : 2);
});
}
});

test("export versions follow the dataset", async (t) => {
const served = {
findings: [
Expand Down