/** * Download/Print transform (Pro): hand out a watermarked copy of the PDF * instead of the original file. Copies are kept for the page's lifetime, * so printing after downloading doesn't stamp again. */ import type { FileTransform } from '../flipper/reader/fileActions'; /** Larger files are not stamped in the browser (memory); the action is refused. */ const MAX_BYTES = 150 * 1024 * 1024; const copies = new Map>(); function notice(container: HTMLElement, text: string, tone: 'busy' | 'error'): () => void { container.querySelector('.pdfrack-notice')?.remove(); const el = document.createElement('div'); el.className = `pdfrack-notice pdfrack-notice-${tone}`; el.setAttribute('role', tone === 'error' ? 'alert' : 'status'); el.innerHTML = tone === 'busy' ? '' : ''; el.appendChild(document.createTextNode(text)); container.appendChild(el); const close = () => el.remove(); if (tone === 'error') window.setTimeout(close, 6000); return close; } async function makeCopy(url: string): Promise { const res = await fetch(url, { credentials: 'same-origin' }); if (!res.ok) throw new Error(`HTTP ${res.status}`); const size = Number(res.headers.get('content-length')) || 0; if (size > MAX_BYTES) { void res.body?.cancel(); // stop downloading the rest throw new Error('too-large'); } const bytes = await res.arrayBuffer(); if (bytes.byteLength > MAX_BYTES) throw new Error('too-large'); const { stampPdf } = await import('./stampPdf'); return URL.createObjectURL(await stampPdf(bytes)); } export function watermarkTransform(container: HTMLElement): FileTransform { return async (url) => { let copy = copies.get(url); if (!copy) { copy = makeCopy(url); copies.set(url, copy); copy.catch(() => copies.delete(url)); } const close = notice(container, 'Preparing a watermarked copy…', 'busy'); try { return await copy; } catch (error) { notice(container, (error as Error).message === 'too-large' ? 'This file is too large to watermark here.' : 'Could not prepare a watermarked copy of this file.', 'error'); throw error; } finally { close(); } }; }