#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
import { http, HttpResponse, delay } from "msw";
import type {
Source,
SourceKpi,
SourcePolicyRef,
SourceStatus,
SourceView,
SourcesResponse,
} from "@processor/api/sources";
import { sampleDailySeries } from "@processor/mocks/sampleDailySeries";
/**
* Stateful mock for the Sources surface so the portal works fully offline with
* mocks on. Mirrors the real backend shape (`/api/v1/sources`, SourceController +
* SourceOverviewService): create/delete mutate an in-memory store, and delete of
* a still-referenced source returns 409. With mocks OFF these calls fall through
* to the real backend instead, like any other `/api/v1/...` surface.
*/
interface StoredSource extends Source {
id: string;
}
function seedSources(): StoredSource[] {
return [
{
id: "src-claims",
name: "Claims intake",
type: "folder",
options: { directory: "/data/claims-intake", mode: "consume" },
enabled: true,
owner: "[email protected]",
},
{
id: "src-contracts",
name: "Contracts drop",
type: "folder",
options: { directory: "/data/contracts", mode: "snapshot" },
enabled: true,
owner: "[email protected]",
},
{
id: "src-archive",
name: "Archive reprocess",
type: "folder",
options: { directory: "/data/archive", mode: "consume" },
enabled: true,
owner: "[email protected]",
},
{
id: "src-legacy",
name: "Legacy share (paused)",
type: "folder",
options: { directory: "/mnt/legacy" },
enabled: false,
owner: "[email protected]",
},
{
id: "src-webhook",
name: "Partner uploads",
type: "webhook",
options: {
webhookId: "whk_demo_5f3a9c21b7",
signingSecret: "whsec_demo_2b8e1d47a9f60c35",
},
enabled: true,
owner: "[email protected]",
},
];
}
/** Which seeded policies reference each seeded source (drives reference counts). */
const references: Record<string, SourcePolicyRef[]> = {
"src-claims": [
{ id: "pol_security", name: "Security Policy" },
{ id: "pol_redaction", name: "Redaction Policy" },
],
"src-contracts": [{ id: "pol_contract", name: "Contract Review" }],
};
/** Per-source document throughput, mirroring the backend's docsTotal / 24h / 30d. */
const docCounts: Record<
string,
{ total: number; last24h: number; last30d: number }
> = {
"src-claims": { total: 45230, last24h: 312, last30d: 9870 },
"src-contracts": { total: 12840, last24h: 96, last30d: 2310 },
"src-archive": { total: 1180, last24h: 0, last30d: 0 },
"src-legacy": { total: 48600, last24h: 0, last30d: 0 },
"src-webhook": { total: 3120, last24h: 24, last30d: 640 },
};
function docsFor(id: string): {
total: number;
last24h: number;
last30d: number;
daily: number[];
} {
const counts = docCounts[id] ?? { total: 0, last24h: 0, last30d: 0 };
return { ...counts, daily: sampleDailySeries(counts.last30d / 30) };
}
let store: StoredSource[] = seedSources();
let idCounter = 0;
function nextId(): string {
idCounter += 1;
return `src_${Date.now().toString(36)}_${idCounter}`;
}
function randomToken(): string {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
}
function refsFor(id: string): SourcePolicyRef[] {
return references[id] ?? [];
}
function configRows(options: Record<string, unknown>) {
const secret = /secret|password|token/i;
return Object.entries(options).map(([key, value]) => ({
label: key.charAt(0).toUpperCase() + key.slice(1),
value: secret.test(key) ? "********" : String(value),
}));
}
function deriveStatus(
source: StoredSource,
referenceCount: number,
): SourceStatus {
if (!source.enabled) return "disabled";
return referenceCount === 0 ? "unused" : "active";
}
function toSourceView(
source: StoredSource,
refs: SourcePolicyRef[],
): SourceView {
const docs = docsFor(source.id);
const webhookId = source.options.webhookId;
return {
id: source.id,
name: source.name,
type: source.type,
status: deriveStatus(source, refs.length),
referenceCount: refs.length,
referencingPolicies: refs,
config: configRows(source.options),
docsTotal: docs.total,
docs24h: docs.last24h,
docs30d: docs.last30d,
webhookPath:
source.type === "webhook" && typeof webhookId === "string"
? `/api/v1/webhooks/${webhookId}`
: null,
};
}
function buildKpis(views: SourceView[]): SourceKpi[] {
const total = views.length;
const inUse = views.filter((v) => v.referenceCount > 0).length;
return [
{ value: total, description: "connections" },
{ value: inUse, description: "referenced by a policy" },
{ value: total - inUse, description: "unused" },
];
}
/** The built-in editor source's demo throughput, mirroring the backend's per-team counters. */
const editorDocs = { total: 8230, last24h: 42, last30d: 1680 };
/** The always-present editor row, pinned first and never editable/deletable. */
function editorView(): SourceView {
return {
id: "editor",
name: "Editor",
type: "editor",
status: "active",
referenceCount: 2,
referencingPolicies: [
{ id: "pol_security", name: "Security Policy" },
{ id: "pol_redaction", name: "Redaction Policy" },
],
config: [],
docsTotal: editorDocs.total,
docs24h: editorDocs.last24h,
docs30d: editorDocs.last30d,
};
}
function buildOverview(): SourcesResponse {
const persisted = store
.map((s) => toSourceView(s, refsFor(s.id)))
.sort(
(a, b) =>
b.referenceCount - a.referenceCount || a.name.localeCompare(b.name),
);
// KPIs describe the configured connections; the built-in editor is pinned first but not counted.
return { kpis: buildKpis(persisted), sources: [editorView(), ...persisted] };
}
export const sourcesHandlers = [
http.get("/api/v1/sources", async () => {
await delay(120);
return HttpResponse.json(buildOverview());
}),
http.get("/api/v1/sources/:id", async ({ params }) => {
await delay(120);
const source = store.find((s) => s.id === params.id);
if (!source) return new HttpResponse(null, { status: 404 });
return HttpResponse.json(source);
}),
http.get("/api/v1/sources/:id/document-counts", async ({ params }) => {
await delay(120);
if (params.id === "editor") {
return HttpResponse.json(sampleDailySeries(editorDocs.last30d / 30));
}
const source = store.find((s) => s.id === params.id);
if (!source) return new HttpResponse(null, { status: 404 });
return HttpResponse.json(docsFor(source.id).daily);
}),
http.post("/api/v1/sources", async ({ request }) => {
await delay(120);
const incoming = (await request.json()) as Source;
const existing = incoming.id
? store.find((s) => s.id === incoming.id)
: undefined;
const id = existing?.id ?? nextId();
let options = incoming.options ?? {};
if (incoming.type === "webhook" && !existing && !options.webhookId) {
options = {
...options,
webhookId: `whk_${randomToken()}`,
signingSecret: `whsec_${randomToken()}`,
};
}
const saved: StoredSource = {
...incoming,
options,
id,
owner: existing?.owner ?? "[email protected]",
};
store = existing
? store.map((s) => (s.id === id ? saved : s))
: [...store, saved];
return HttpResponse.json(saved);
}),
http.delete("/api/v1/sources/:id", async ({ params }) => {
await delay(120);
const id = String(params.id);
if (id === "editor") {
return HttpResponse.json(
{ detail: "The editor is a built-in source and cannot be deleted" },
{ status: 400 },
);
}
const source = store.find((s) => s.id === id);
if (!source) return new HttpResponse(null, { status: 404 });
const refs = refsFor(id);
if (refs.length > 0) {
return HttpResponse.json(
{
detail: `Source is referenced by ${refs.length} policy(ies): ${refs
.map((r) => r.name)
.join(", ")}`,
},
{ status: 409 },
);
}
store = store.filter((s) => s.id !== id);
return new HttpResponse(null, { status: 204 });
}),
];