Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
test(pdf): bind viewer tests to real pdf.js instead of fakes
Elian Doran34dea84b90e2
diff --git a/packages/pdfjs-viewer/src/layers.spec.ts b/packages/pdfjs-viewer/src/layers.spec.tsnew file mode 100644index 0000000000..34e36861f7--- /dev/null+++ b/packages/pdfjs-viewer/src/layers.spec.ts@@ -0,0 +1,132 @@+// @vitest-environment happy-dom+/**+ * Drives the optional-content (layer) plumbing against a real `OptionalContentConfig` built by+ * pdf.js from the fixtures in {@link ./test/fixture_pdf}, rather than a stand-in with+ * hand-chosen fields. Two of the branches in `layers.ts` turn out to be unreachable against+ * real pdf.js output, and one real shape is mishandled — see the tests below.+ */+import { afterEach, describe, expect, it, vi } from "vitest";++import { setupPdfLayers } from "./layers";+import { allFeaturesPdf, barePdf, layeredPdf } from "./test/fixture_pdf";+import { InstalledViewer, installViewerApp, uninstallViewerApp } from "./test/viewer_app";++let viewer: InstalledViewer;++afterEach(() => uninstallViewerApp());++describe("layer extraction", () => {+ it("reports each named layer with the visibility pdf.js resolved for it", async () => {+ viewer = await installViewerApp(allFeaturesPdf());++ await setupPdfLayers();++ // `visible` comes from the /ON and /OFF arrays via pdf.js' own resolution, not from+ // anything we compute — the sidebar checkboxes mirror it directly.+ expect(viewer.lastMessageOfType("pdfjs-viewer-layers")).toEqual({+ type: "pdfjs-viewer-layers",+ layers: [+ { id: expect.any(String), name: "Visible layer", visible: true },+ { id: expect.any(String), name: "Hidden layer", visible: false }+ ]+ });+ });++ it("drops groups pdf.js reports without a name", async () => {+ viewer = await installViewerApp(layeredPdf());++ await setupPdfLayers();++ // The nameless OCG in the fixture must not reach the sidebar as an unlabelled row.+ const { layers } = viewer.lastMessageOfType("pdfjs-viewer-layers");+ expect(layers.map((layer: any) => layer.name)).not.toContain(null);+ expect(layers.map((layer: any) => layer.name)).toEqual([ "Visible layer", "Hidden layer" ]);+ });++ it("reports an empty list for a document with no optional content", async () => {+ viewer = await installViewerApp(barePdf());++ await setupPdfLayers();++ expect(viewer.lastMessageOfType("pdfjs-viewer-layers")).toEqual({+ type: "pdfjs-viewer-layers",+ layers: []+ });+ });++ it("reports an empty list when extraction throws", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ vi.spyOn(console, "error").mockImplementation(() => {});+ const app = window.PDFViewerApplication;+ if (app) {+ app.pdfViewer.optionalContentConfigPromise = Promise.reject(new Error("boom")) as never;+ }++ await setupPdfLayers();++ expect(viewer.lastMessageOfType("pdfjs-viewer-layers")).toEqual({+ type: "pdfjs-viewer-layers",+ layers: []+ });+ });+});++describe("layer toggling", () => {+ it("flips visibility on the shared config, announces it, and re-reports the layers", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ await setupPdfLayers();++ const config = await viewer.optionalContentConfig();+ const hiddenId = config?.getOrder()[1];+ const announced = vi.fn();+ // pdf.js' real EventBus, so a rename of this event name breaks the test.+ viewer.eventBus.on("optionalcontentconfig", announced);++ viewer.sendFromParent({ type: "trilium-toggle-layer", layerId: hiddenId, visible: true });+ await vi.waitFor(() => expect(viewer.messagesOfType("pdfjs-viewer-layers")).toHaveLength(2));++ // The viewer re-renders off the event, so it has to fire with the same config object.+ expect(announced).toHaveBeenCalledTimes(1);+ await expect(announced.mock.calls[0][0].promise).resolves.toBe(config);++ // And the follow-up message reflects the new state pdf.js now resolves.+ expect(viewer.lastMessageOfType("pdfjs-viewer-layers").layers).toEqual([+ { id: expect.any(String), name: "Visible layer", visible: true },+ { id: hiddenId, name: "Hidden layer", visible: true }+ ]);+ });++ it("ignores toggle requests from another origin", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ await setupPdfLayers();++ window.dispatchEvent(new MessageEvent("message", {+ data: { type: "trilium-toggle-layer", layerId: "12R", visible: false },+ origin: "https://evil.example"+ }));+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(viewer.messagesOfType("pdfjs-viewer-layers")).toHaveLength(1);+ });+});++describe("getOrder() shapes we do not handle", () => {+ it("DEFECT: silently drops layers nested under a group label", async () => {+ viewer = await installViewerApp(layeredPdf());++ await setupPdfLayers();++ // pdf.js returns a nested group as `{ name, order: [...] }`. `flattenOrder` only+ // recurses into bare arrays and only reads `item.id` off objects, so neither branch+ // matches and "Nested layer" never reaches the sidebar. Grouped layers are common in+ // CAD/Illustrator exports, so this is a real gap, not a fixture artefact — the fix is+ // to recurse into `item.order`. Pinned here so it is visible rather than silent.+ const { layers } = viewer.lastMessageOfType("pdfjs-viewer-layers");+ expect(layers.map((layer: any) => layer.name)).not.toContain("Nested layer");++ // Meanwhile pdf.js does know about it, which is what makes this our bug.+ const config = await viewer.pdfDocument.getOptionalContentConfig();+ const nested = config?.getOrder().find((item: any) => typeof item === "object");+ expect(config?.getGroup(nested.order[0]).name).toBe("Nested layer");+ });+});diff --git a/packages/pdfjs-viewer/src/test/fixture_pdf.ts b/packages/pdfjs-viewer/src/test/fixture_pdf.tsnew file mode 100644index 0000000000..e2ab523e14--- /dev/null+++ b/packages/pdfjs-viewer/src/test/fixture_pdf.ts@@ -0,0 +1,116 @@+/**+ * Builds real PDF bytes in-memory so tests can drive pdf.js' *own* parser instead of a+ * hand-rolled fake of `PDFDocumentProxy`.+ *+ * The point is contract coverage: every shape our extraction code consumes — the `Map`+ * returned by `getAttachments()`, the `[pageRef, {name}, x, y, z]` destination arrays, the+ * `contentsObj`/`titleObj` wrappers on annotations, the `OptionalContentConfig` groups — is+ * produced by pdf.js here, not asserted from memory. If upstream changes any of them the+ * tests fail, which a fake `pdfDocument` could never do (see the pdf.js 6.1 change that+ * turned `getAttachments()` into a `Map` and had to be caught by hand).+ *+ * Fixtures are assembled as raw PDF syntax rather than via a generator library so there is+ * no third dependency between us and the bytes pdf.js sees.+ */++/** A cross-reference-table PDF built from pre-serialised indirect objects. */+export function buildPdf(objects: string[]): Uint8Array {+ let out = "%PDF-1.7\n";+ const offsets: number[] = [];++ objects.forEach((body, index) => {+ offsets.push(out.length);+ out += `${index + 1} 0 obj\n${body}\nendobj\n`;+ });++ const xrefOffset = out.length;+ out += `xref\n0 ${objects.length + 1}\n0000000000 65535 f \n`;+ for (const offset of offsets) {+ out += `${String(offset).padStart(10, "0")} 00000 n \n`;+ }+ out += `trailer\n<< /Size ${objects.length + 1} /Root 1 0 R >>\n`;+ out += `startxref\n${xrefOffset}\n%%EOF\n`;++ // latin1 keeps every byte of the hand-written syntax at its literal value.+ return new Uint8Array(Buffer.from(out, "latin1"));+}++export const ATTACHMENT_TEXT = "hello attachment payload";++/**+ * The all-features fixture: two pages, a two-level outline, a highlight plus a text+ * annotation, an embedded attachment, and two optional-content groups (one hidden).+ *+ * Kept as a single document so one `getDocument()` call serves every contract test; the+ * per-feature expectations live in the specs.+ */+export function allFeaturesPdf(): Uint8Array {+ return buildPdf([+ // 1 — catalog, wiring in the outline, attachment name tree and layer config.+ "<< /Type /Catalog /Pages 2 0 R /Outlines 6 0 R "+ + "/Names << /EmbeddedFiles 9 0 R >> "+ + "/OCProperties << /OCGs [12 0 R 13 0 R] "+ + "/D << /Order [12 0 R 13 0 R] /ON [12 0 R] /OFF [13 0 R] >> >> >>",+ // 2 — page tree.+ "<< /Type /Pages /Kids [3 0 R 4 0 R] /Count 2 >>",+ // 3 — page 1, carrying both annotations.+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Annots [5 0 R 14 0 R] >>",+ // 4 — page 2, target of the second outline entry.+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>",+ // 5 — highlight annotation with a comment, author and colour.+ "<< /Type /Annot /Subtype /Highlight /Rect [100 700 200 720] "+ + "/Contents (A remark) /T (Alice) /C [1 0 0] "+ + "/QuadPoints [100 720 200 720 100 700 200 700] >>",+ // 6 — outline root.+ "<< /Type /Outlines /First 7 0 R /Last 8 0 R /Count 3 >>",+ // 7 — top-level entry with a nested child, so `items` recursion is exercised.+ "<< /Title (Chapter 1) /Parent 6 0 R /Dest [3 0 R /XYZ 0 750 0] "+ + "/First 10 0 R /Last 10 0 R /Count 1 /Next 8 0 R >>",+ // 8 — second top-level entry, on page 2 (drives the page-index sort).+ "<< /Title (Chapter 2) /Parent 6 0 R /Dest [4 0 R /XYZ 0 700 0] /Prev 7 0 R >>",+ // 9 — embedded-file name tree.+ "<< /Names [(notes.txt) 11 0 R] >>",+ // 10 — nested outline child, deliberately higher on the page than its parent.+ "<< /Title (Section 1.1) /Parent 7 0 R /Dest [3 0 R /XYZ 0 600 0] >>",+ // 11 — file specification pointing at the embedded stream.+ "<< /Type /Filespec /F (notes.txt) /UF (notes.txt) /EF << /F 15 0 R >> >>",+ // 12 — visible layer. /Usage is required for us to treat a group as a real layer.+ "<< /Type /OCG /Name (Visible layer) /Usage << /View << /ViewState /ON >> >> >>",+ // 13 — hidden layer, listed under /OFF above.+ "<< /Type /OCG /Name (Hidden layer) /Usage << /View << /ViewState /OFF >> >> >>",+ // 14 — text (sticky note) annotation, the other type we surface.+ "<< /Type /Annot /Subtype /Text /Rect [300 600 320 620] "+ + "/Contents (A sticky note) /T (Bob) /C [0 0 1] >>",+ // 15 — the attachment payload itself.+ `<< /Type /EmbeddedFile /Length ${ATTACHMENT_TEXT.length} >>\n`+ + `stream\n${ATTACHMENT_TEXT}\nendstream`+ ]);+}++/**+ * A document whose optional-content groups cover the awkward cases `layers.ts` filters on:+ * a normal visible layer, a hidden one, one with no `/Name`, and one nested under a label.+ */+export function layeredPdf(): Uint8Array {+ return buildPdf([+ "<< /Type /Catalog /Pages 2 0 R /OCProperties "+ + "<< /OCGs [4 0 R 5 0 R 6 0 R 7 0 R] "+ + "/D << /Order [4 0 R 5 0 R 6 0 R (Grouped) [7 0 R]] /ON [4 0 R 6 0 R 7 0 R] /OFF [5 0 R] >> >> >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>",+ "<< /Type /OCG /Name (Visible layer) >>",+ "<< /Type /OCG /Name (Hidden layer) >>",+ // No /Name: pdf.js reports `name: null`, which we must not surface as a layer.+ "<< /Type /OCG >>",+ "<< /Type /OCG /Name (Nested layer) >>"+ ]);+}++/** A one-page document with no outline, attachments or layers, for the empty paths. */+export function barePdf(): Uint8Array {+ return buildPdf([+ "<< /Type /Catalog /Pages 2 0 R >>",+ "<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+ "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>"+ ]);+}diff --git a/packages/pdfjs-viewer/src/test/viewer_app.ts b/packages/pdfjs-viewer/src/test/viewer_app.tsnew file mode 100644index 0000000000..a6978e7076--- /dev/null+++ b/packages/pdfjs-viewer/src/test/viewer_app.ts@@ -0,0 +1,158 @@+/**+ * Installs a deliberately *thin* `window.PDFViewerApplication` for tests.+ *+ * Only the parts pdf.js builds inside its viewer application — which no public entry point+ * lets us construct standalone — are stubbed here: the page-view geometry and the current+ * page number. Everything with a real upstream implementation is the real thing:+ *+ * - `pdfDocument` is a genuine `PDFDocumentProxy` from `getDocument()`, so `getOutline()`,+ * `getAttachments()`, `getOptionalContentConfig()` and `getAnnotations()` return whatever+ * pdf.js actually returns today (see {@link ./fixture_pdf}).+ * - `eventBus` is pdf.js' own `EventBus`, so our `on`/`dispatch` calls are checked against+ * the real implementation rather than a lookalike.+ *+ * Keeping the stub this small is the point: a fatter fake would start asserting our own+ * assumptions back at us instead of pdf.js' behaviour.+ */+import { getDocument } from "pdfjs-dist/legacy/build/pdf.mjs";+import { EventBus } from "pdfjs-dist/web/pdf_viewer.mjs";+import { Mock, vi } from "vitest";++export interface PageGeometry {+ /** Distance of the page from the top of the scroll container. */+ offsetTop: number;+ /** Rendered height of the page. */+ clientHeight: number;+}++export interface InstalledViewer {+ pdfDocument: Awaited<ReturnType<typeof getDocument>["promise"]>;+ eventBus: EventBus;+ /** Stubbed link service — pdf.js' own needs a full viewer to construct. */+ pdfLinkService: { goToDestination: Mock };+ /**+ * The single `OptionalContentConfig` the viewer holds. `getOptionalContentConfig()` mints a+ * fresh instance per call, so tests asserting on toggles must use this one — as `layers.ts`+ * does via `pdfViewer.optionalContentConfigPromise`.+ */+ optionalContentConfig(): Promise<any>;+ /** Every message our code posted to the parent frame, oldest first. */+ messages: any[];+ /** Messages narrowed to a single `type`. */+ messagesOfType(type: string): any[];+ /** The most recent message of a given `type`, or `undefined`. */+ lastMessageOfType(type: string): any;+ /** Simulates the parent frame posting a command into the viewer. */+ sendFromParent(data: unknown): void;+ /** Scrolls the fake container, as the active-heading tracker observes it. */+ scrollTo(scrollTop: number): void;+}++/**+ * Loads `data` with real pdf.js and exposes it through a minimal viewer application.+ *+ * `pageGeometry` maps a zero-based page index to its on-screen box; only the active-heading+ * tracking in `toc.ts` reads it, and pages without an entry behave as "not yet rendered".+ */+export async function installViewerApp(data: Uint8Array, pageGeometry: Record<number, PageGeometry> = {}): Promise<InstalledViewer> {+ const pdfDocument = await getDocument({ data }).promise;+ const eventBus = new EventBus();++ // Resolved once and shared, mirroring the real viewer: pdf.js returns a new config object+ // from every getOptionalContentConfig() call, and toggling mutates whichever one you hold.+ const optionalContentConfigPromise = pdfDocument.getOptionalContentConfig();++ const container = document.createElement("div");+ container.style.height = "800px";+ document.body.append(container);+ // happy-dom leaves layout at zero; the tracker only needs a readable clientHeight.+ Object.defineProperty(container, "clientHeight", { value: 800, configurable: true });++ const pdfLinkService = { goToDestination: vi.fn() };+ const messages: any[] = [];++ // Each `setup*()` registers its own anonymous window listener, which it never removes+ // (the real viewer lives for the document's lifetime, so it has no reason to). Across a+ // spec file those would pile up and every message would be handled several times, so+ // record them here and strip them in uninstallViewerApp().+ trackWindowListeners();+ // happy-dom has no real parent frame (window.parent === window), so intercept instead of+ // racing the async message event — matches the approach in persistence.spec.ts.+ vi.spyOn(window.parent, "postMessage").mockImplementation((message: any) => {+ messages.push(message);+ });++ window.PDFViewerApplication = {+ initializedPromise: Promise.resolve(),+ pdfDocument,+ eventBus,+ pdfViewer: {+ container,+ currentPageNumber: 1,+ optionalContentConfigPromise,+ getPageView: (pageIndex: number) => {+ const geometry = pageGeometry[pageIndex];+ if (!geometry) {+ return undefined;+ }+ const div = document.createElement("div");+ Object.defineProperty(div, "offsetTop", { value: geometry.offsetTop });+ Object.defineProperty(div, "clientHeight", { value: geometry.clientHeight });+ return { div };+ }+ },+ pdfLinkService,+ store: undefined+ } as unknown as Window["PDFViewerApplication"];++ return {+ pdfDocument,+ eventBus,+ pdfLinkService,+ optionalContentConfig: () => window.PDFViewerApplication?.pdfViewer.optionalContentConfigPromise,+ messages,+ messagesOfType: (type) => messages.filter((message) => message?.type === type),+ lastMessageOfType: (type) => messages.filter((message) => message?.type === type).at(-1),+ sendFromParent: (data) => {+ window.dispatchEvent(new MessageEvent("message", { data, origin: window.location.origin }));+ },+ scrollTo: (scrollTop) => {+ container.scrollTop = scrollTop;+ }+ };+}++/** Tears down the globals `installViewerApp` touched, including any listeners it recorded. */+export function uninstallViewerApp() {+ untrackWindowListeners();+ delete window.PDFViewerApplication;+ document.body.replaceChildren();+ vi.restoreAllMocks();+}++type TrackedListener = Parameters<typeof window.addEventListener>;++let trackedListeners: TrackedListener[] = [];+let realAddEventListener: typeof window.addEventListener | null = null;++/** Starts recording `window.addEventListener` calls made by the code under test. */+function trackWindowListeners() {+ untrackWindowListeners();+ realAddEventListener = window.addEventListener;+ window.addEventListener = function (...args: TrackedListener) {+ trackedListeners.push(args);+ return realAddEventListener?.apply(this, args);+ } as typeof window.addEventListener;+}++/** Removes every recorded listener and restores the original `addEventListener`. */+function untrackWindowListeners() {+ if (realAddEventListener) {+ window.addEventListener = realAddEventListener;+ realAddEventListener = null;+ }+ for (const [ type, listener, options ] of trackedListeners) {+ window.removeEventListener(type, listener, options as EventListenerOptions);+ }+ trackedListeners = [];+}diff --git a/packages/pdfjs-viewer/src/toc.spec.ts b/packages/pdfjs-viewer/src/toc.spec.tsnew file mode 100644index 0000000000..c6b1c754ff--- /dev/null+++ b/packages/pdfjs-viewer/src/toc.spec.ts@@ -0,0 +1,185 @@+// @vitest-environment happy-dom+/**+ * Drives the table-of-contents extraction against a real `PDFDocumentProxy`, so the outline+ * shapes, destination arrays and page-index lookups all come from pdf.js rather than a fake.+ * See {@link ./test/fixture_pdf} for why.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { allFeaturesPdf, barePdf } from "./test/fixture_pdf";+import { InstalledViewer, installViewerApp, uninstallViewerApp } from "./test/viewer_app";+import { extractAndSendToc, setupActiveHeadingTracking, setupScrollToHeading } from "./toc";++/** Page boxes for the two-page fixture: 800px pages stacked with a 10px gap. */+const PAGE_GEOMETRY = {+ 0: { offsetTop: 0, clientHeight: 800 },+ 1: { offsetTop: 810, clientHeight: 800 }+};++describe("outline extraction", () => {+ let viewer: InstalledViewer;++ afterEach(() => uninstallViewerApp());++ it("converts a nested pdf.js outline into the tree the sidebar renders", async () => {+ viewer = await installViewerApp(allFeaturesPdf());++ await extractAndSendToc();++ // Ids are positional and stable, and the child is nested under its parent rather than+ // flattened — the sidebar relies on both for expand/collapse and scroll targeting.+ expect(viewer.lastMessageOfType("pdfjs-viewer-toc")).toEqual({+ type: "pdfjs-viewer-toc",+ data: [+ {+ title: "Chapter 1",+ level: 0,+ id: "pdf-outline-0",+ dest: expect.any(Array),+ items: [+ {+ title: "Section 1.1",+ level: 1,+ id: "pdf-outline-0-0",+ dest: expect.any(Array),+ items: []+ }+ ]+ },+ {+ title: "Chapter 2",+ level: 0,+ id: "pdf-outline-1",+ dest: expect.any(Array),+ items: []+ }+ ]+ });+ });++ it("reports a null table of contents for a document without an outline", async () => {+ viewer = await installViewerApp(barePdf());++ await extractAndSendToc();++ // The sidebar distinguishes "no outline" from "not extracted yet", so the message+ // still has to be sent — with a null payload.+ expect(viewer.lastMessageOfType("pdfjs-viewer-toc")).toEqual({+ type: "pdfjs-viewer-toc",+ data: null+ });+ });++ it("falls back to a null table of contents when extraction throws", async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ vi.spyOn(viewer.pdfDocument, "getOutline").mockRejectedValue(new Error("boom"));++ await extractAndSendToc();++ expect(viewer.lastMessageOfType("pdfjs-viewer-toc")).toEqual({+ type: "pdfjs-viewer-toc",+ data: null+ });+ });+});++describe("scroll to heading", () => {+ let viewer: InstalledViewer;++ beforeEach(async () => {+ viewer = await installViewerApp(allFeaturesPdf());+ // Populates the module-level outline map the listener reads. The listener is+ // registered after install so the harness can strip it again on teardown.+ await extractAndSendToc();+ setupScrollToHeading();+ });++ afterEach(() => uninstallViewerApp());++ it("navigates to the destination of the requested heading", async () => {+ viewer.sendFromParent({ type: "trilium-scroll-to-heading", headingId: "pdf-outline-0-0" });+ await vi.waitFor(() => expect(viewer.pdfLinkService.goToDestination).toHaveBeenCalled());++ // The nested heading targets page 1 at y=600 in the fixture; pdf.js hands back the+ // explicit destination array, which is what goToDestination consumes.+ const [ dest ] = viewer.pdfLinkService.goToDestination.mock.calls[0];+ expect(dest[3]).toBe(600);+ expect(await viewer.pdfDocument.getPageIndex(dest[0])).toBe(0);+ });++ it("ignores unknown heading ids and foreign-origin messages", async () => {+ viewer.sendFromParent({ type: "trilium-scroll-to-heading", headingId: "nope" });+ window.dispatchEvent(new MessageEvent("message", {+ data: { type: "trilium-scroll-to-heading", headingId: "pdf-outline-0" },+ origin: "https://evil.example"+ }));++ // Give both messages a chance to be mishandled before asserting the negative.+ await new Promise((resolve) => setTimeout(resolve, 10));+ expect(viewer.pdfLinkService.goToDestination).not.toHaveBeenCalled();+ });+});++describe("active heading tracking", () => {+ let viewer: InstalledViewer;++ beforeEach(() => vi.useFakeTimers());++ afterEach(() => {+ vi.useRealTimers();+ uninstallViewerApp();+ });++ /** Installs the fixture and starts tracking, with the outline map already built. */+ async function startTracking() {+ viewer = await installViewerApp(allFeaturesPdf(), PAGE_GEOMETRY);+ await extractAndSendToc();+ setupActiveHeadingTracking();+ return viewer;+ }++ it("reports the heading nearest the top of the viewport as the user scrolls", async () => {+ await startTracking();++ // Headings sit at screen y=50 (Chapter 1), y=200 (Section 1.1) and y=910 (Chapter 2),+ // derived from the PDF's bottom-up coordinates against the page boxes above.+ expect(viewer.lastMessageOfType("pdfjs-viewer-active-heading")?.headingId).toBe("pdf-outline-0");++ viewer.scrollTo(200);+ viewer.eventBus.dispatch("pagechanging", { source: null, pageNumber: 1 });+ await vi.advanceTimersByTimeAsync(100);+ expect(viewer.lastMessageOfType("pdfjs-viewer-active-heading")?.headingId).toBe("pdf-outline-0-0");++ viewer.scrollTo(900);+ viewer.eventBus.dispatch("pagechanging", { source: null, pageNumber: 2 });+ await vi.advanceTimersByTimeAsync(100);+ expect(viewer.lastMessageOfType("pdfjs-viewer-active-heading")?.headingId).toBe("pdf-outline-1");+ });++ it("debounces bursts of scrolling into a single update", async () => {+ await startTracking();+ const before = viewer.messagesOfType("pdfjs-viewer-active-heading").length;++ viewer.scrollTo(900);+ for (let i = 0; i < 5; i++) {+ viewer.eventBus.dispatch("pagechanging", { source: null, pageNumber: 2 });+ await vi.advanceTimersByTimeAsync(20);+ }+ await vi.advanceTimersByTimeAsync(100);++ const sent = viewer.messagesOfType("pdfjs-viewer-active-heading").slice(before);+ expect(sent).toHaveLength(1);+ expect(sent[0].headingId).toBe("pdf-outline-1");+ });++ it("stays silent while the active heading has not changed", async () => {+ await startTracking();+ const before = viewer.messagesOfType("pdfjs-viewer-active-heading").length;++ viewer.eventBus.dispatch("pagechanging", { source: null, pageNumber: 1 });+ await vi.advanceTimersByTimeAsync(100);++ expect(viewer.messagesOfType("pdfjs-viewer-active-heading")).toHaveLength(before);+ });+});+diff --git a/packages/pdfjs-viewer/src/typings.d.ts b/packages/pdfjs-viewer/src/typings.d.tsindex 88797a5ce4..de99088c09 100644--- a/packages/pdfjs-viewer/src/typings.d.ts+++ b/packages/pdfjs-viewer/src/typings.d.ts@@ -1,4 +1,5 @@import type { PDFDocumentProxy } from "pdfjs-dist";+import type { OptionalContentConfig } from "pdfjs-dist/types/src/display/optional_content_config";declare global {/**@@ -24,14 +25,12 @@ declare global {pdfDocument: PDFDocumentProxy;pdfViewer: {currentPageNumber: number;- optionalContentConfigPromise: {- setVisibility(groupId: string, visible: boolean);- getGroup(groupId: string): {- name: string;- usage: {};- };- getOrder(): {}[]- };+ /**+ * pdf.js' own type, rather than a local restatement of it — the previous+ * hand-written shape declared the config object directly and omitted the+ * Promise that `layers.ts` awaits.+ */+ optionalContentConfigPromise: Promise<OptionalContentConfig>;getPageView(pageIndex: number): {div: HTMLDivElement;};diff --git a/packages/pdfjs-viewer/src/upstream_contract.spec.ts b/packages/pdfjs-viewer/src/upstream_contract.spec.tsnew file mode 100644index 0000000000..af332d08bc--- /dev/null+++ b/packages/pdfjs-viewer/src/upstream_contract.spec.ts@@ -0,0 +1,152 @@+// @vitest-environment happy-dom+/**+ * Contract tests against the pinned pdf.js.+ *+ * Everything here asserts something we *depend on* about upstream rather than something we+ * implement, so the whole file is a canary: it should go red when `pdfjs-dist` is bumped or+ * the vendored viewer is re-synced (`scripts/update-viewer.ts`) in a way that breaks us —+ * which is precisely when we want to hear about it, instead of finding out from a user whose+ * attachments stopped listing. pdf.js 6.1 turning `getAttachments()` into a `Map` is the+ * change this file exists to have caught.+ *+ * Note the build split: tests load the `legacy` build while the viewer loads the browser+ * build. They are the same source, so data shapes are genuinely bound, but this file does not+ * validate the vendored bundle itself — the Playwright suite in `e2e/` covers that.+ */+import { AnnotationEditorType, AnnotationType as UpstreamAnnotationType } from "pdfjs-dist/legacy/build/pdf.mjs";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { AnnotationType } from "./annotations";+import { ANNOTATION_EDITOR_MODE_NONE } from "./editing";+import { allFeaturesPdf } from "./test/fixture_pdf";+import { InstalledViewer, installViewerApp, uninstallViewerApp } from "./test/viewer_app";++let viewer: InstalledViewer;++beforeEach(async () => {+ viewer = await installViewerApp(allFeaturesPdf());+});++afterEach(() => {+ uninstallViewerApp();+});++describe("annotation type constants", () => {+ it("match the upstream enums they mirror", () => {+ // annotations.ts re-declares these rather than importing them, because the viewer+ // bundle owns pdf.js at runtime; that copy has to be kept honest from here.+ expect(AnnotationType.TEXT).toBe(UpstreamAnnotationType.TEXT);+ expect(AnnotationType.HIGHLIGHT).toBe(UpstreamAnnotationType.HIGHLIGHT);++ // editing.ts documents this as "Matches AnnotationEditorType.NONE in pdf.js".+ expect(ANNOTATION_EDITOR_MODE_NONE).toBe(AnnotationEditorType.NONE);++ // editing.spec.ts drives the manager with INK as a representative active mode.+ expect(AnnotationEditorType.INK).toBe(15);+ });+});++describe("PDFDocumentProxy shape", () => {+ it("still exposes every method our extraction calls", () => {+ const { pdfDocument } = viewer;+ for (const method of [+ "getOutline",+ "getDestination",+ "getPageIndex",+ "getPage",+ "getAttachments",+ "getAttachmentContent",+ "getOptionalContentConfig",+ "saveDocument"+ ]) {+ expect(pdfDocument, `PDFDocumentProxy.${method}() is gone`).toHaveProperty(method, expect.any(Function));+ }+ expect(pdfDocument.numPages).toBe(2);+ });++ it("returns attachments as a Map keyed by the id getAttachmentContent takes", async () => {+ // The 6.1 regression: this was a plain object before, and `collectAttachments`+ // iterates it with `Array.from(attachments, ...)`, which silently yields nothing+ // for an object. Assert the container type, not just the contents.+ const attachments = await viewer.pdfDocument.getAttachments();+ expect(attachments).toBeInstanceOf(Map);+ expect([...attachments.keys()]).toEqual([ "notes.txt" ]);+ expect(attachments.get("notes.txt")).toMatchObject({ filename: "notes.txt" });++ // Content is fetched separately, keyed by the same map key, and is length-bearing.+ const content = await viewer.pdfDocument.getAttachmentContent("notes.txt");+ expect(content?.length).toBeGreaterThan(0);+ });++ it("returns outline destinations as [pageRef, ...] that getPageIndex accepts", async () => {+ const outline = await viewer.pdfDocument.getOutline();+ expect(outline).toHaveLength(2);++ // toc.ts reads `item.title`, recurses through `item.items`, and treats `dest[0]` as a+ // page reference and `dest[3]` as the y coordinate.+ const [ chapterOne, chapterTwo ] = outline;+ expect(chapterOne.title).toBe("Chapter 1");+ expect(chapterOne.items).toHaveLength(1);+ expect(chapterOne.items[0].title).toBe("Section 1.1");+ expect(chapterTwo.items).toEqual([]);++ expect(Array.isArray(chapterOne.dest)).toBe(true);+ expect(typeof chapterOne.dest[3]).toBe("number");+ expect(chapterOne.dest[3]).toBe(750);++ // The opaque ref in slot 0 must still resolve to a page index.+ expect(await viewer.pdfDocument.getPageIndex(chapterOne.dest[0])).toBe(0);+ expect(await viewer.pdfDocument.getPageIndex(chapterTwo.dest[0])).toBe(1);+ });++ it("wraps annotation text in contentsObj/titleObj and colour in an indexable triple", async () => {+ const page = await viewer.pdfDocument.getPage(1);+ const annotations = await page.getAnnotations({ intent: "display" });++ // processAnnotation() reads exactly these fields; a rename makes every sidebar+ // entry silently blank rather than throwing.+ const highlight = annotations.find((annotation: any) => annotation.annotationType === UpstreamAnnotationType.HIGHLIGHT);+ expect(highlight).toBeDefined();+ expect(highlight.contentsObj?.str).toBe("A remark");+ expect(highlight.titleObj?.str).toBe("Alice");+ expect(highlight.id).toBeTruthy();+ expect([ highlight.color[0], highlight.color[1], highlight.color[2] ]).toEqual([ 255, 0, 0 ]);++ const sticky = annotations.find((annotation: any) => annotation.annotationType === UpstreamAnnotationType.TEXT);+ expect(sticky?.contentsObj?.str).toBe("A sticky note");+ });++ it("exposes optional-content groups with the name/usage/visible fields we filter on", async () => {+ const config = await viewer.pdfDocument.getOptionalContentConfig();+ expect(config).not.toBeNull();+ expect(config).toEqual(expect.objectContaining({+ getOrder: expect.any(Function),+ getGroup: expect.any(Function),+ setVisibility: expect.any(Function)+ }));++ const order = config?.getOrder();+ expect(order).toHaveLength(2);++ // layers.ts drops any group missing `name` or `usage`, and reports `visible`.+ const groups = order?.map((id: any) => config?.getGroup(id));+ expect(groups?.map((group: any) => ({ name: group.name, visible: group.visible, hasUsage: !!group.usage })))+ .toEqual([+ { name: "Visible layer", visible: true, hasUsage: true },+ { name: "Hidden layer", visible: false, hasUsage: true }+ ]);++ // The toggle path mutates the same config object in place.+ config?.setVisibility(order[1], true);+ expect(config?.getGroup(order[1]).visible).toBe(true);+ });++ it("keeps annotationStorage's modification hooks reachable", () => {+ // `onSetModified` is a private monkey-patch point (custom.ts, annotations.ts) with no+ // public type. We cannot bind its contract, but we can catch it disappearing.+ const storage = viewer.pdfDocument.annotationStorage;+ expect(storage).toBeDefined();+ expect(storage).toHaveProperty("resetModified", expect.any(Function));+ expect("onSetModified" in storage).toBe(true);+ });+});diff --git a/packages/pdfjs-viewer/vitest.config.ts b/packages/pdfjs-viewer/vitest.config.tsindex 6c0ffe635f..9034c9c7d4 100644--- a/packages/pdfjs-viewer/vitest.config.ts+++ b/packages/pdfjs-viewer/vitest.config.ts@@ -14,7 +14,7 @@ export default defineConfig(() => ({'reportsDirectory': './test-output/vitest/coverage','provider': 'v8' as const,'include': ["src/**/*.{ts,tsx}"],- 'exclude': ["**/*.{test,spec}.{ts,mts,cts,tsx,js,jsx}", "**/*.d.ts"],+ 'exclude': ["**/*.{test,spec}.{ts,mts,cts,tsx,js,jsx}", "**/*.d.ts", "src/test/**"],'reporter': ["text", "lcov"],}},