}
+ {preview.bytes && }
+ {preview.status !== 'idle' && }
+ >
+}
```
-`readDocumentPreview` reads are bounded to 2 MiB and omit credentials and referrers.
-HTTP 401 and 403 responses become `DocumentPreviewError` with reason `expired`;
-other HTTP failures and responses without a readable body become `unavailable`,
-and oversized reads become `too-large`; these errors omit signed URLs and response bodies.
-Network, stream, CORS and abort errors propagate unchanged. Cross-origin document URLs must
-allow CORS reads from the application origin.
-
-RTF parsing and rich Markdown are bounded to 256 KiB; larger Markdown is shown as literal text.
-RTF above 256 KiB and any document above 2 MiB render `errorFallback` and call `onError`.
-Markdown skips embedded HTML and shows every image as its alt text without loading it.
-Links render only for absolute `http:`, `https:` and `mailto:` URLs; other links render as plain
-text. RTF is parsed locally, strips active content and embedded resources, and renders in a sandbox
-with a restrictive content security policy. PDF frames use the browser's
-PDF renderer; supply an authorized HTTP(S) URL on a separate user-content origin whose response
-has a verified PDF MIME type. Viewer always rejects non-HTTP(S) locations, including `blob:`,
-`data:` and `javascript:` URLs. It rejects the page's exact origin unless `allowSameOrigin` is set;
-other subdomains of the same site pass this check. The application must verify the PDF MIME type
-and origin isolation; Viewer does not check the response MIME type or sandbox the PDF frame.
-An application with a trusted PDF-only route can explicitly set `allowSameOrigin`; that route must
-verify the response is a PDF and must never serve arbitrary uploaded HTML. Use `errorFallback`
-for a rejected location. Arbitrary HTML and Office documents are not embedded.
-
-`className` styles the Markdown/text article or the RTF iframe. `richClassName` styles rendered
-Markdown only, and `textClassName` styles the literal text view.
-
-Document chunk-load and parser failures render `errorFallback` and notify `onError`. Unmount and
-reopen the preview to create a fresh React lazy loader after a failed chunk request.
-PDF server rendering waits for the client origin before
-deciding whether a URL is allowed, without showing a premature error.
+Opening fetches the authorized `mediaUrl` with omitted credentials and referrer. Cross-origin responses need CORS. The hook accepts the same version-bound identity and expiry clock as playback. It can renew once per attempt, before reading an expiring grant or after HTTP 401/403. Closing, unmounting, retrying or changing asset/version cancels the old attempt. Status moves from `idle` to `loading`, then `ready` or `error`. A 401 is `expired`, a 403 is `forbidden`, and other fetch failures are `network`. `onError(reason)` on document and PDF.js renderers also distinguishes `too-large`, `parse`, and `unsupported`. Applications own translated errors, retry buttons and original downloads.
+
+The hook reads at most 2 MiB of text or Markdown plus the stream chunk needed to detect overflow. Pass its `truncated` flag to Viewer for a visible notice and its response `mime` for decoding. When passing your own bytes, supply the corresponding MIME, including its charset. A Unicode BOM takes priority. Unknown encodings fall back to UTF-8. Markdown above 256 KiB displays a notice and literal text. Rich Markdown skips embedded HTML, shows images as alt text, and permits only absolute HTTP(S) and mailto links. RTF requires a complete document of at most 256 KiB. Its formatting-only output is rendered in a sandboxed iframe. Use `colorScheme="dark"` or `"auto"` to override the default light rendering.
+
+Existing callers can still use `readDocumentPreview(url, signal)` from `/documents`. This strict reader returns an ArrayBuffer and rejects oversized reads. Its original HTTP error categories are preserved. Reopening a document remounts its lazy renderer after a chunk-load error.
+
+### PDF pages on phones
+
+```tsx
+import '@transloadit/viewer/viewer.css'
+import { Viewer } from '@transloadit/viewer/react/viewer'
+
+
+```
+
+Serve the worker exported at `@transloadit/viewer/pdf.worker.mjs` as a JavaScript module on the application's own origin. Copy it at build time and update it together with the package. Bundlers that emit assets for `new URL('./pdf.worker.min.mjs', import.meta.url)` can omit `workerSrc`. Other bundlers need the explicit public path above. For example, run in your ESM build script after creating the destination directory:
+
+```ts
+import { copyFile } from 'node:fs/promises'
+
+await copyFile(new URL(import.meta.resolve('@transloadit/viewer/pdf.worker.mjs')), 'public/assets/pdf.worker.min.mjs')
+```
+
+The document must be served directly from the authorized, separate HTTP(S) origin with CORS and a verified PDF MIME. PDF.js mode checks the GET response, rejects redirects, and omits credentials and the referrer. A trusted PDF-only application endpoint may explicitly set `allowSameOrigin`. Downloads are capped at 64 MiB. One page canvas is fitted to the container and limited to four million backing pixels. The previous canvas is released on navigation or resize. Tab to the reader or its buttons. Left/Right move one page, Home/End jump to the ends, and Escape bubbles to the host dialog. Supply `loadingFallback`, `errorFallback` or `unsupportedFallback` to customize feedback. Remount the reader to retry the same URL.
+
+A strict CSP can allow `script-src 'self'`, `worker-src 'self'`, `style-src 'self'` and `connect-src 'self' https://your-file-origin.example`. Serve chunks and the worker directly on the app origin. The canvas reader requires neither a blob worker nor unsafe evaluation. For PDFs using predefined CMaps, standard font files, ICC profiles, or supplementary image decoders, serve the matching `pdfjs-dist` directories (`cmaps/`, `standard_fonts/`, `iccs/`, `wasm/`) under a same-origin public directory and set `assetBaseUrl="/assets/pdfjs/"`. The reader selects the JavaScript decoder fallback when available.
+
+`mode="frame"` remains the default and uses the browser's inline PDF reader. It passes native iframe attributes, including `onLoad`, through to the frame. Provide `unsupportedFallback` (for example a download link) for browsers that report no inline PDF support. For this mode allow your verified file host in `frame-src`. The host must enforce PDF MIME and origin isolation for the entire navigation. Browser frame load events cannot identify HTTP authorization failures. Office documents require conversion to PDF upstream.
+
+### Document styles
+
+Import `@transloadit/viewer/viewer.css` to opt into default document typography, link colors, wrapping, and page controls. Override `--tl-viewer-font`, `--tl-viewer-color`, `--tl-viewer-background`, `--tl-viewer-padding`, and `--tl-viewer-link` on an ancestor. `className` styles the Markdown/text article or RTF iframe, `richClassName` styles rendered Markdown, and `textClassName` styles literal text. RTF frame content uses its own color scheme.
diff --git a/packages/img/package.json b/packages/img/package.json
index 3e436eea..0a7eb1bd 100644
--- a/packages/img/package.json
+++ b/packages/img/package.json
@@ -16,7 +16,8 @@
"files": [
"dist",
"docs",
- "README.md"
+ "README.md",
+ "viewer.css"
],
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
@@ -81,20 +82,24 @@
"./documents": {
"types": "./dist/document.d.ts",
"default": "./dist/document.js"
- }
+ },
+ "./viewer.css": "./viewer.css",
+ "./pdf.worker.mjs": "./dist/pdf.worker.min.mjs"
},
"scripts": {
- "build": "../../node_modules/.bin/tsc --build tsconfig.build.json",
+ "build": "../../node_modules/.bin/tsc --build tsconfig.build.json && node ./scripts/copy-pdf-worker.ts",
"check": "yarn lint:ts && yarn test:unit",
"lint:ts": "../../node_modules/.bin/tsc --build tsconfig.build.json && ../../node_modules/.bin/tsc --noEmit --project tsconfig.json",
"prepack": "yarn build",
- "test:unit": "yarn build && ../../node_modules/.bin/vitest run ./test"
+ "test:unit": "yarn build && ../../node_modules/.bin/vitest run ./test",
+ "test:browser": "yarn build && playwright test --config browser/playwright.config.ts"
},
"dependencies": {
"@noble/ciphers": "^1.3.0",
"@transloadit/utils": "^4.10.1",
"hast-util-to-jsx-runtime": "^2.3.0",
"hls.js": "^1.6.16",
+ "pdfjs-dist": "6.5.438",
"remark-gfm": "^4.0.1",
"remark-parse": "^11.0.0",
"remark-rehype": "^11.1.0",
@@ -120,6 +125,7 @@
}
},
"devDependencies": {
+ "@playwright/test": "1.64.0",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"esbuild": "^0.28.2",
diff --git a/packages/img/scripts/copy-pdf-worker.ts b/packages/img/scripts/copy-pdf-worker.ts
new file mode 100644
index 00000000..cdcf9cbd
--- /dev/null
+++ b/packages/img/scripts/copy-pdf-worker.ts
@@ -0,0 +1,7 @@
+import { copyFile } from 'node:fs/promises'
+
+// The worker must match the parser version, including after a dependency upgrade.
+await copyFile(
+ new URL(import.meta.resolve('pdfjs-dist/legacy/build/pdf.worker.min.mjs')),
+ new URL('../dist/pdf.worker.min.mjs', import.meta.url),
+)
diff --git a/packages/img/src/document.ts b/packages/img/src/document.ts
index 22630eed..6afdce2c 100644
--- a/packages/img/src/document.ts
+++ b/packages/img/src/document.ts
@@ -1,95 +1,86 @@
+import { DocumentPreviewError, readPreviewContent } from './readPreviewContent.ts'
+
+export type { DocumentPreviewReason } from './readPreviewContent.ts'
+
+export { DocumentPreviewError } from './readPreviewContent.ts'
+
/** Document formats Viewer can display without sending bytes to another service. */
export type DocumentPreviewKind = 'pdf' | 'markdown' | 'text' | 'rtf'
+export type ViewerKind = DocumentPreviewKind | 'audio' | 'image' | 'video'
-/**
- * PDF requires application/pdf. Markdown, RTF and text may use the filename when MIME is null,
- * application/octet-stream or text/plain.
- */
+/** Choose a preview from catalog metadata. PDF detection alone does not authorize embedding. */
export function documentPreviewKind(
- mime: string | null,
+ mime: string | null | undefined,
filename: string,
): DocumentPreviewKind | null {
- const type = mime?.split(';', 1)[0]?.trim().toLowerCase() ?? null
+ const type = mime?.split(';', 1)[0]?.trim().toLowerCase()
if (type === 'application/pdf') return 'pdf'
if (type === 'text/markdown' || type === 'text/x-markdown') return 'markdown'
if (type === 'application/rtf' || type === 'text/rtf' || type === 'application/x-rtf')
return 'rtf'
- if (type !== null && type !== 'application/octet-stream' && type !== 'text/plain') return null
- const extension = filename.split('.').at(-1)?.toLowerCase()
- if (extension === 'md' || extension === 'markdown') return 'markdown'
- if (extension === 'rtf') return 'rtf'
- if (extension === 'txt' || type === 'text/plain') return 'text'
+ if (
+ type &&
+ /^(?:text\/(?:csv|tab-separated-values|yaml|x-yaml|log)|application\/(?:json|yaml|x-yaml|[\w.+-]+\+json))$/.test(
+ type,
+ )
+ )
+ return 'text'
+ if (type && type !== 'application/octet-stream' && type !== 'text/plain') return null
+ if (/\.pdf$/i.test(filename) && type !== 'text/plain') return 'pdf'
+ if (/\.(?:md|markdown|mdown|mkdn?|mkdown|mdwn)$/i.test(filename)) return 'markdown'
+ if (/\.rtf$/i.test(filename)) return 'rtf'
+ if (/\.(?:txt|csv|tsv|json|log|ya?ml)$/i.test(filename) || type === 'text/plain') return 'text'
return null
}
-/** Text previews stay bounded even when an origin omits or misreports Content-Length. */
-export const MAX_DOCUMENT_PREVIEW_BYTES = 2 * 1024 * 1024
+/** Classify media and documents consistently across lists and detail views. */
+export function viewerKind(mime: string | null | undefined, filename: string): ViewerKind | null {
+ const family = mime?.trim().toLowerCase().split('/')[0]
+ if (mime?.includes('/') && (family === 'image' || family === 'video' || family === 'audio'))
+ return family
+ return documentPreviewKind(mime, filename)
+}
-/** Rich document parsers keep a smaller bound than literal text. */
+export const MAX_DOCUMENT_PREVIEW_BYTES = 2 * 1024 * 1024
export const MAX_RICH_DOCUMENT_PREVIEW_BYTES = 256 * 1024
-/** HTTP and size error categories whose messages omit signed URLs and response bodies. */
-export class DocumentPreviewError extends Error {
- readonly reason: 'too-large' | 'expired' | 'unavailable'
-
- constructor(reason: DocumentPreviewError['reason']) {
- super(`Document preview ${reason}`)
- this.reason = reason
- }
-}
-
-/**
- * Read an authorized, CORS-readable URL with a streaming size limit. HTTP and size failures use
- * DocumentPreviewError; network, stream and abort errors propagate unchanged.
- */
+/** Original strict reader, including its 0.2 HTTP error categories. */
export async function readDocumentPreview(url: string, signal: AbortSignal): Promise {
- const response = await fetch(url, { signal, credentials: 'omit', referrerPolicy: 'no-referrer' })
- if (!response.ok) {
- await response.body?.cancel()
- throw new DocumentPreviewError(
- response.status === 401 || response.status === 403 ? 'expired' : 'unavailable',
- )
- }
- if (Number(response.headers.get('content-length')) > MAX_DOCUMENT_PREVIEW_BYTES) {
- await response.body?.cancel()
- throw new DocumentPreviewError('too-large')
- }
- if (response.body === null) throw new DocumentPreviewError('unavailable')
- const reader = response.body.getReader()
- const chunks: Uint8Array[] = []
- let length = 0
try {
- while (true) {
- signal.throwIfAborted()
- const { done, value } = await reader.read()
- if (done) break
- length += value.byteLength
- if (length > MAX_DOCUMENT_PREVIEW_BYTES) {
- await reader.cancel()
- throw new DocumentPreviewError('too-large')
- }
- chunks.push(value)
+ return (await readPreviewContent(url, signal, { limit: MAX_DOCUMENT_PREVIEW_BYTES })).bytes
+ } catch (error) {
+ if (error instanceof DocumentPreviewError) {
+ if (error.reason === 'forbidden') throw new DocumentPreviewError('expired')
+ if (error.reason === 'network') throw new DocumentPreviewError('unavailable')
}
- } finally {
- reader.releaseLock()
- }
- const bytes = new Uint8Array(length)
- let offset = 0
- for (const chunk of chunks) {
- bytes.set(chunk, offset)
- offset += chunk.byteLength
+ throw error
}
- return bytes.buffer
}
-/** Preserve UTF-8 and Unicode text exports with a UTF-16 byte-order mark. */
-export function decodeDocumentText(buffer: ArrayBuffer): string {
- const bytes = new Uint8Array(buffer)
- const encoding =
- bytes[0] === 0xff && bytes[1] === 0xfe
- ? 'utf-16le'
- : bytes[0] === 0xfe && bytes[1] === 0xff
- ? 'utf-16be'
- : 'utf-8'
- return new TextDecoder(encoding).decode(bytes)
+/** A Unicode BOM takes precedence over the MIME charset. Unknown labels fall back to UTF-8. */
+export function decodeDocumentText(
+ buffer: ArrayBuffer,
+ mime?: string | null,
+ truncated = false,
+): string {
+ const bytes = new Uint8Array(
+ buffer,
+ 0,
+ truncated ? Math.min(buffer.byteLength, MAX_DOCUMENT_PREVIEW_BYTES) : buffer.byteLength,
+ )
+ let encoding = /;\s*charset\s*=\s*(?:"([^"]+)"|([^;\s]+))/i
+ .exec(mime ?? '')
+ ?.slice(1)
+ .find(Boolean)
+ if (bytes[0] === 0xff && bytes[1] === 0xfe) encoding = 'utf-16le'
+ else if (bytes[0] === 0xfe && bytes[1] === 0xff) encoding = 'utf-16be'
+ else if (bytes[0] === 0xef && bytes[1] === 0xbb && bytes[2] === 0xbf) encoding = 'utf-8'
+ let decoder: TextDecoder
+ try {
+ decoder = new TextDecoder(encoding)
+ } catch {
+ decoder = new TextDecoder()
+ }
+ // A partial multibyte character at the truncation boundary belongs to the omitted suffix.
+ return decoder.decode(bytes, { stream: truncated || bytes.byteLength < buffer.byteLength })
}
diff --git a/packages/img/src/documentViewer.tsx b/packages/img/src/documentViewer.tsx
index 29884e4e..373b3bc8 100644
--- a/packages/img/src/documentViewer.tsx
+++ b/packages/img/src/documentViewer.tsx
@@ -3,7 +3,7 @@
import type { Components } from 'hast-util-to-jsx-runtime'
import type { ReactNode } from 'react'
-import type { DocumentPreviewKind } from './document.ts'
+import type { DocumentPreviewKind, DocumentPreviewReason } from './document.ts'
import { toJsxRuntime } from 'hast-util-to-jsx-runtime'
import { Component, Fragment, useEffect, useMemo, useRef, useState } from 'react'
@@ -38,7 +38,10 @@ export interface DocumentViewerProps {
/** Shown when document loading, parsing or size validation fails. */
errorFallback?: ReactNode
/** Reports a document loading, parsing or size failure. */
- onError?: () => void
+ onError?: (reason: DocumentPreviewReason) => void
+ mime?: string | null
+ truncated?: boolean
+ colorScheme?: 'light' | 'dark' | 'auto'
}
const markdownProcessor = unified().use(remarkParse).use(remarkGfm).use(remarkRehype)
@@ -61,6 +64,7 @@ function RichText({
bytes,
title,
className,
+ colorScheme,
loadingFallback,
errorFallback,
onError,
@@ -78,7 +82,7 @@ function RichText({
let active = true
// RTF's parser is loaded only when a rich-text document is actually opened.
void import('./renderRtfPreview.ts')
- .then(({ renderRtfPreview }) => renderRtfPreview(bytes))
+ .then(({ renderRtfPreview }) => renderRtfPreview(bytes, colorScheme))
.then(
(html) => {
if (active) setResult({ bytes, html })
@@ -86,17 +90,18 @@ function RichText({
() => {
if (!active) return
setResult({ bytes, failed: true })
- reportError.current?.()
+ reportError.current?.('parse')
},
)
return () => {
active = false
}
- }, [bytes])
+ }, [bytes, colorScheme])
if (result?.bytes !== bytes) return loadingFallback
if (result.failed || result.html === undefined) return errorFallback
return (