Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

PdfDocumentNavigation.ts

93 lines3.5 KB

1import { constVoid } from "effect/Function";
2import type { CDPSession } from "playwright-core";
3​
4const escapeHtml = (value: string) =>
5 value.replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;");
6​
7export const isPdfAssetUrl = (url: string) => {
8 const { pathname } = new URL(url);
9 return pathname.startsWith("/api/assets/") && /\.pdf$/i.test(pathname);
10};
11​
12/**
13 * A session has one `Fetch.enable`, so HTTP auth challenges share it. Chromium
14 * raises `Fetch.authRequired` only for requests a pattern intercepts.
15 */
16export async function installPdfDocumentNavigation(
17 cdp: CDPSession,
18 { handleAuthRequests }: { readonly handleAuthRequests: boolean },
19) {
20 const nativeViewer = await cdp.send("Runtime.evaluate", {
21 expression: "navigator.pdfViewerEnabled",
22 returnByValue: true,
23 });
24 const interceptPdfs = nativeViewer.result?.value !== true;
25 if (!interceptPdfs && !handleAuthRequests) return;
26 const { frameTree } = await cdp.send("Page.getFrameTree");
27 // The shell cannot open PDFs. Commit a document at the original URL so the
28 // client can embed its signed bytes while Back and Forward keep working.
29 cdp.on("Fetch.requestPaused", (event) => {
30 const { requestId, request, frameId } = event;
31 const proceed = () => cdp.send("Fetch.continueRequest", { requestId });
32 void (async () => {
33 if (
34 !interceptPdfs ||
35 request.method !== "GET" ||
36 frameId !== frameTree.frame.id ||
37 !isPdfAssetUrl(request.url)
38 ) {
39 await proceed();
40 return;
41 }
42 const status = event.responseStatusCode;
43 if (status === undefined || (status >= 300 && status < 400)) {
44 await proceed();
45 return;
46 }
47 const contentType = event.responseHeaders
48 ?.find((header) => header.name.toLowerCase() === "content-type")
49 ?.value.split(";", 1)[0]
50 ?.trim()
51 .toLowerCase();
52 if (status < 200 || status >= 300 || contentType !== "application/pdf") {
53 // Reach the browser's requestfailed path instead of committing a successful PDF tab.
54 await cdp.send("Fetch.failRequest", { requestId, errorReason: "Failed" });
55 return;
56 }
57 const name = escapeHtml(
58 decodeURIComponent(new URL(request.url).pathname.split("/").at(-1) ?? "PDF"),
59 );
60 await cdp.send("Fetch.fulfillRequest", {
61 requestId,
62 responseCode: 200,
63 responseHeaders: [
64 { name: "Content-Type", value: "text/html; charset=utf-8" },
65 { name: "Cache-Control", value: "no-store" },
66 { name: "Content-Security-Policy", value: "default-src 'none'; sandbox" },
67 { name: "X-Content-Type-Options", value: "nosniff" },
68 ],
69 body: Buffer.from(
70 `<!doctype html><html><head><title>${name}</title></head><body><h1>${name}</h1><p>This PDF is displayed in the connected client.</p></body></html>`,
71 ).toString("base64"),
72 });
73 })().catch(() => proceed().catch(constVoid));
74 });
75 // Only document navigations pause; the client's PDF fetch gets the original bytes.
76 await cdp.send("Fetch.enable", {
77 patterns: [
78 ...(interceptPdfs
79 ? [
80 {
81 urlPattern: "*/api/assets/*",
82 resourceType: "Document",
83 requestStage: "Response",
84 } as const,
85 ]
86 : []),
87 ...(handleAuthRequests
88 ? [{ urlPattern: "*", resourceType: "Document", requestStage: "Request" } as const]
89 : []),
90 ],
91 handleAuthRequests,
92 });