Reorganize repo structure and standards references

This commit is contained in:
david committed 2026-06-29 05:03:42 +02:00
1 parent 3cb93a81be
commit be2054274d
5885 files changed
+2588 -195

No files matched your search

@@ -0,0 +1,77 @@
import { describe, expect, it } from "vitest";
import { ExportTableValidationError } from "../types.js";
import { buildPdfExportArtifact, serializeExportTableToPdf } from "./index.js";
const PDF_HEADER = "%PDF-";
function decodeHeader(bytes: Uint8Array): string {
return new TextDecoder().decode(bytes.slice(0, PDF_HEADER.length));
}
describe("@toolctrl/exports/pdf public entrypoint", () => {
it("exposes PDF helpers through the dedicated subpath", async () => {
const exportsModule = await import("./index.js");
expect(Object.keys(exportsModule).sort()).toEqual([
"ExportPdfRowLimitExceededError",
"ExportTableValidationError",
"PDF_STREAM_HARD_ROW_LIMIT",
"buildPdfExportArtifact",
"serializeExportTableToPdf",
"serializeExportTableToPdfStream",
]);
});
});
describe("serializeExportTableToPdf", () => {
it("renders PDF bytes with explicit title, header labels, and column order", async () => {
const bytes = await serializeExportTableToPdf(
{
columns: [
{ key: "email", label: "Email address" },
{ key: "id", label: "Identifier" },
"active",
],
rows: [{ id: 7, email: "ada@example.com", active: true, ignored: "not exported" }],
},
{ title: "Member export" },
);
expect(decodeHeader(bytes)).toBe(PDF_HEADER);
expect(bytes.byteLength).toBeGreaterThan(0);
});
it("rejects malformed row input through the PDF API", async () => {
await expect(
serializeExportTableToPdf({
rows: [{ id: 1 }, null],
} as never),
).rejects.toThrow(new ExportTableValidationError("Export table row at index 1 must be an object record."));
});
it("rejects duplicate columns through the PDF API", async () => {
await expect(
serializeExportTableToPdf({
columns: ["id", { key: "id", label: "Identifier" }],
rows: [{ id: 1 }],
}),
).rejects.toThrow(new ExportTableValidationError('Export table columns contain duplicate key "id".'));
});
});
describe("buildPdfExportArtifact", () => {
it("returns PDF bytes with binary export metadata", async () => {
const artifact = await buildPdfExportArtifact({
columns: ["id"],
rows: [{ id: 1 }, { id: 2 }],
});
expect(decodeHeader(artifact.bytes)).toBe(PDF_HEADER);
expect(artifact.contentType).toBe("application/pdf");
expect(artifact.extension).toBe("pdf");
expect(artifact.rowCount).toBe(2);
expect(artifact.byteLength).toBe(artifact.bytes.byteLength);
expect(artifact.byteLength).toBeGreaterThan(0);
});
});
@@ -0,0 +1,194 @@
import type { Writable } from "node:stream";
import React from "react";
import { Document, Page, StyleSheet, Text, View, renderToBuffer, renderToStream } from "@react-pdf/renderer";
import { PDF_STREAM_HARD_ROW_LIMIT } from "../format-caps.js";
import { type ExportTable, normalizeExportTable } from "../types.js";
export { ExportTableValidationError } from "../types.js";
export type { ExportColumn, ExportPrimitive, ExportRecord, ExportTable } from "../types.js";
const PDF_CONTENT_TYPE = "application/pdf";
/**
* PDF rendering cost grows super-linearly with row count and produces
* unusable >500-page documents above this threshold. The cap protects
* both the worker and downstream UX.
*/
export { PDF_STREAM_HARD_ROW_LIMIT };
export class ExportPdfRowLimitExceededError extends Error {
readonly code = "EXPORT_PDF_ROW_LIMIT_EXCEEDED";
constructor(rowCount: number) {
super(
`PDF export exceeds the ${PDF_STREAM_HARD_ROW_LIMIT}-row hard cap (got ${rowCount}); use CSV or XLSX for larger datasets.`,
);
this.name = "ExportPdfRowLimitExceededError";
}
}
export type PdfExportOptions = {
title?: string;
};
export type PdfExportArtifact = {
bytes: Uint8Array;
contentType: typeof PDF_CONTENT_TYPE;
extension: "pdf";
rowCount: number;
byteLength: number;
};
const styles = StyleSheet.create({
page: {
padding: 32,
fontSize: 10,
fontFamily: "Helvetica",
},
title: {
fontSize: 16,
fontWeight: 700,
marginBottom: 16,
},
table: {
display: "flex",
flexDirection: "column",
width: "100%",
borderTopWidth: 1,
borderLeftWidth: 1,
borderColor: "#d1d5db",
},
row: {
display: "flex",
flexDirection: "row",
},
headerCell: {
flexGrow: 1,
flexBasis: 0,
padding: 6,
fontWeight: 700,
backgroundColor: "#f3f4f6",
borderRightWidth: 1,
borderBottomWidth: 1,
borderColor: "#d1d5db",
},
cell: {
flexGrow: 1,
flexBasis: 0,
padding: 6,
borderRightWidth: 1,
borderBottomWidth: 1,
borderColor: "#d1d5db",
},
});
export async function serializeExportTableToPdf(
table: ExportTable,
options: PdfExportOptions = {},
): Promise<Uint8Array> {
const normalizedTable = normalizeExportTable(table);
const document = React.createElement(
Document,
{ title: options.title },
React.createElement(
Page,
{ size: "A4", style: styles.page },
options.title === undefined ? null : React.createElement(Text, { style: styles.title }, options.title),
React.createElement(
View,
{ style: styles.table },
React.createElement(
View,
{ style: styles.row },
...normalizedTable.columns.map((column) =>
React.createElement(Text, { key: column.key, style: styles.headerCell }, column.label),
),
),
...normalizedTable.rows.map((row, rowIndex) =>
React.createElement(
View,
{ key: `row-${rowIndex}`, style: styles.row },
...normalizedTable.columns.map((column) =>
React.createElement(Text, { key: column.key, style: styles.cell }, row[column.key]),
),
),
),
),
),
);
return new Uint8Array(await renderToBuffer(document));
}
export async function buildPdfExportArtifact(
table: ExportTable,
options: PdfExportOptions = {},
): Promise<PdfExportArtifact> {
const normalizedTable = normalizeExportTable(table);
const bytes = await serializeExportTableToPdf(table, options);
return {
bytes,
contentType: PDF_CONTENT_TYPE,
extension: "pdf",
rowCount: normalizedTable.rowCount,
byteLength: bytes.byteLength,
};
}
/**
* Streaming PDF writer. Uses `@react-pdf/renderer`'s renderToStream and
* pipes the resulting Readable into `writeStream`. Enforces a hard cap of
* {@link PDF_STREAM_HARD_ROW_LIMIT} rows up front — PDF cost is
* super-linear and unbounded exports produce unusable artefacts.
*/
export async function serializeExportTableToPdfStream(
writeStream: Writable,
table: ExportTable,
options: PdfExportOptions = {},
): Promise<{ rowCount: number }> {
const normalizedTable = normalizeExportTable(table);
if (normalizedTable.rowCount > PDF_STREAM_HARD_ROW_LIMIT) {
throw new ExportPdfRowLimitExceededError(normalizedTable.rowCount);
}
const document = React.createElement(
Document,
{ title: options.title },
React.createElement(
Page,
{ size: "A4", style: styles.page },
options.title === undefined ? null : React.createElement(Text, { style: styles.title }, options.title),
React.createElement(
View,
{ style: styles.table },
React.createElement(
View,
{ style: styles.row },
...normalizedTable.columns.map((column) =>
React.createElement(Text, { key: column.key, style: styles.headerCell }, column.label),
),
),
...normalizedTable.rows.map((row, rowIndex) =>
React.createElement(
View,
{ key: `row-${rowIndex}`, style: styles.row },
...normalizedTable.columns.map((column) =>
React.createElement(Text, { key: column.key, style: styles.cell }, row[column.key]),
),
),
),
),
),
);
const readable = await renderToStream(document);
await new Promise<void>((resolve, reject) => {
readable.on("error", reject);
writeStream.on("error", reject);
readable.on("end", () => resolve());
readable.pipe(writeStream, { end: false });
});
return { rowCount: normalizedTable.rowCount };
}
@@ -0,0 +1,49 @@
import { PassThrough } from "node:stream";
import { describe, expect, it } from "vitest";
import {
ExportPdfRowLimitExceededError,
PDF_STREAM_HARD_ROW_LIMIT,
serializeExportTableToPdfStream,
} from "./index.js";
async function collect(stream: PassThrough): Promise<Buffer> {
const chunks: Buffer[] = [];
for await (const chunk of stream) {
chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
return Buffer.concat(chunks);
}
describe("serializeExportTableToPdfStream", () => {
it("renders a valid PDF prelude for small tables", async () => {
const sink = new PassThrough();
const collected = collect(sink);
const rows = Array.from({ length: 10 }, (_, i) => ({ id: i, name: `name-${i}` }));
const result = await serializeExportTableToPdfStream(sink, {
columns: [
{ key: "id", label: "Identifier" },
{ key: "name", label: "Name" },
],
rows,
}, { title: "Member export" });
sink.end();
expect(result).toEqual({ rowCount: 10 });
const buffer = await collected;
expect(buffer.slice(0, 5).toString("utf8")).toBe("%PDF-");
expect(buffer.byteLength).toBeGreaterThan(100);
});
it("rejects exports above the 5k-row hard cap", async () => {
const sink = new PassThrough();
sink.on("data", () => undefined);
const rows = Array.from({ length: PDF_STREAM_HARD_ROW_LIMIT + 1 }, (_, i) => ({ id: i }));
await expect(
serializeExportTableToPdfStream(sink, { columns: ["id"], rows }),
).rejects.toBeInstanceOf(ExportPdfRowLimitExceededError);
});
});