Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,5 @@ jobs:
- run: pnpm install --frozen-lockfile
- run: pnpm exec playwright install --with-deps firefox
- run: pnpm test -- --run
- run: pnpm build
# Builds the package, then tests the Vite plugin on an app bundled from that build.
- run: pnpm test:plugin
7 changes: 7 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@ Build the package:
pnpm build
```

Test the Vite plugin. This builds the package, bundles a small app from it and opens the app in
Firefox:

```bash
pnpm test:plugin
```

The test and build scripts synchronize the PDF.js runtime assets before
running. The PDF.js release archive is required because the viewer assets are
not published in this repository. Do not commit generated `dist` or `public`
Expand Down
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,22 @@ npm install @missing-elements/pdfjs-viewer
import '@missing-elements/pdfjs-viewer'
```

Vite, webpack 5 and Next.js bundle the viewer with no configuration. They don't copy the PDF.js data folders, though, because PDF.js loads those files by name. Without them, scanned pages compressed with JBIG2, CCITT or JPEG 2000 render blank or black, CJK text in fonts the PDF doesn't embed goes missing, and JavaScript in PDFs doesn't run. To support every PDF, copy the package's `dist` folder into your public files, for example in a `postinstall` script, and point [`assets-base`](https://missing-elements.github.io/pdfjs-viewer/#hosting) at it:
Vite, webpack 5 and Next.js bundle the viewer with no configuration. They don't copy the PDF.js data folders, though, because PDF.js loads those files by name. Without them, scanned pages compressed with JBIG2, CCITT or JPEG 2000 render blank or black, CJK text in fonts the PDF doesn't embed goes missing, and JavaScript in PDFs doesn't run.

With Vite, add the plugin that ships with the package. It writes the data into the build output, next to the viewer files: about 3.4 MB, which a browser downloads only for a document that needs it.

```js
// vite.config.js
import { pdfjsViewerData } from '@missing-elements/pdfjs-viewer/vite'

export default {
plugins: [pdfjsViewerData()]
}
```

The data files keep the names PDF.js asks for, with no hash in them. If your server caches the whole `assets` folder as `immutable`, leave them out of that rule, or browsers keep the old files after you upgrade.

With webpack, Next.js or another bundler, copy the package's `dist` folder into your public files, for example in a `postinstall` script, and point [`assets-base`](https://missing-elements.github.io/pdfjs-viewer/#hosting) at it:

```html
<pdfjs-viewer-element src="/file.pdf" assets-base="/pdfjs-viewer/"></pdfjs-viewer-element>
Expand Down
6 changes: 6 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@
"types": "./types/pdfjs-viewer-element.d.ts",
"default": "./dist/pdfjs-viewer-element.js"
},
"./vite": {
"types": "./plugins/vite.d.ts",
"default": "./plugins/vite.js"
},
"./dist/*": "./dist/*",
"./package.json": "./package.json"
},
Expand All @@ -45,6 +49,7 @@
},
"files": [
"dist",
"plugins",
"types"
],
"publishConfig": {
Expand All @@ -55,6 +60,7 @@
"dev": "vite",
"build": "pnpm sync:pdfjs && tsc && vite build && node scripts/copy-worker.mjs",
"test": "pnpm sync:pdfjs && vitest",
"test:plugin": "pnpm build && vitest run --config vitest.plugin.config.ts",
"coverage": "pnpm sync:pdfjs && vitest run --coverage",
"release": "node scripts/release.mjs",
"release:dry": "node scripts/release.mjs --dry-run"
Expand Down
7 changes: 7 additions & 0 deletions plugins/vite.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/**
* A Vite plugin. It writes the PDF.js data the viewer loads on demand (`wasm/`, `cmaps/`,
* `standard_fonts/`, `iccs/`, `images/` and `pdf.sandbox.mjs`) into the build output, next to the
* viewer files Vite emits. The element finds the data there, with no `assets-base` or resource
* attribute.
*/
export declare function pdfjsViewerData(): { name: string }
52 changes: 52 additions & 0 deletions plugins/vite.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import { readdirSync, readFileSync, statSync } from 'node:fs'
import { join, posix } from 'node:path'
import { fileURLToPath } from 'node:url'

// A bundler emits the viewer's runtime files under hashed names and leaves the PDF.js data behind:
// PDF.js asks for those files by name from a folder URL, so nothing references them one by one.
// The element looks for the data next to two of the runtime files (`RESOURCE_OPTIONS` in
// src/pdfjs-viewer-element.ts). This plugin finds those two files in the build output and writes
// the data next to them, under the names PDF.js expects.
const distDirectory = fileURLToPath(new URL('../dist', import.meta.url))

const dataByAnchor = {
'viewer.mjs': ['cmaps', 'iccs', 'images', 'standard_fonts', 'wasm'],
'pdf.mjs': ['pdf.sandbox.mjs']
}

const readFile = (file) => readFileSync(join(distDirectory, file))

const listFiles = (entry) => {
const path = join(distDirectory, entry)
if (!statSync(path).isDirectory()) return [entry]
return readdirSync(path).map((name) => posix.join(entry, name))
}

// The bundler copies a runtime file byte for byte and only renames it, so an emitted asset is
// recognised by its content. That follows any `assetFileNames` setting, and it works in Vite and
// Rollup versions that don't record which source file an asset came from.
const isSameFile = (source, file) =>
Buffer.byteLength(source) === file.length && file.equals(Buffer.from(source))

export const pdfjsViewerData = () => ({
name: 'pdfjs-viewer-data',
generateBundle(_options, bundle) {
const anchors = Object.entries(dataByAnchor).map(([name, entries]) => ({ file: readFile(name), entries }))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: anchors reads both dist anchor files eagerly on every build, even when the bundle has no viewer asset. Read them only when a candidate asset needs comparing, so apps that don't use the viewer don't pay for it or fail when dist is absent.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At plugins/vite.js, line 34:

<comment>`anchors` reads both `dist` anchor files eagerly on every build, even when the bundle has no viewer asset. Read them only when a candidate asset needs comparing, so apps that don't use the viewer don't pay for it or fail when `dist` is absent.</comment>

<file context>
@@ -0,0 +1,52 @@
+export const pdfjsViewerData = () => ({
+  name: 'pdfjs-viewer-data',
+  generateBundle(_options, bundle) {
+    const anchors = Object.entries(dataByAnchor).map(([name, entries]) => ({ file: readFile(name), entries }))
+
+    Object.values(bundle)
</file context>


Object.values(bundle)
.filter((output) => output.type === 'asset')
.forEach((asset) => {
const anchor = anchors.find(({ file }) => isSameFile(asset.source, file))
if (!anchor) return

const outputDirectory = posix.dirname(asset.fileName)
anchor.entries.flatMap(listFiles).forEach((file) => {
this.emitFile({
type: 'asset',
fileName: posix.join(outputDirectory, file),
source: readFile(file)
})
})
})
}
})
2 changes: 1 addition & 1 deletion scripts/copy-worker.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ const targetFile = resolve(distDir, 'pdf.worker.min.mjs')
const targetRendererFile = resolve(distDir, 'pdf.renderer.min.mjs')
const targetSandboxFile = resolve(distDir, 'pdf.sandbox.mjs')
// Resources PDF.js loads only for documents that need them. The element defaults their URLs to
// these folders next to viewer.mjs.
// these folders next to viewer.mjs, and plugins/vite.js copies the same folders into a bundled app.
const resourceDirs = ['cmaps', 'iccs', 'standard_fonts', 'wasm']
const targetPdfFile = resolve(distDir, 'pdf.mjs')
const targetViewerFile = resolve(distDir, 'viewer.mjs')
Expand Down
3 changes: 2 additions & 1 deletion src/pdfjs-viewer-element.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ const DEFAULTS = {
// Resources PDF.js loads only for documents that need them. They ship in the package `dist`
// folder, and each defaults to `fileName` resolved against the runtime file named by `base`, so
// `assets-base` and the individual runtime URLs carry them along. Bundlers emit the runtime files
// but not these folders, so bundled apps set `assets-base` or the attributes.
// but not these folders, so bundled apps add the build plugin (plugins/vite.js), which writes the
// folders next to the emitted files, or set `assets-base` or the attributes.
// PDF.js fetches most of them from its worker, which runs from a `blob:` URL where relative paths
// don't resolve, so attribute values are made absolute, and folder URLs get the trailing slash
// PDF.js requires.
Expand Down
11 changes: 11 additions & 0 deletions tests/fixtures/bundled-app/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Bundled app</title>
</head>
<body>
<pdfjs-viewer-element src="/ccitt-g4.pdf" style="height: 100dvh"></pdfjs-viewer-element>
<script type="module" src="./main.js"></script>
</body>
</html>
2 changes: 2 additions & 0 deletions tests/fixtures/bundled-app/main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
// The built package, as an installed app imports it.
import '../../../dist/pdfjs-viewer-element.js'
Binary file added tests/fixtures/ccitt-g4.pdf
Binary file not shown.
178 changes: 178 additions & 0 deletions tests/plugin/vite.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
import { copyFileSync, createReadStream, mkdtempSync, readdirSync, readFileSync, rmSync, statSync } from 'node:fs'
import { createServer, type Server } from 'node:http'
import { createRequire } from 'node:module'
import type { AddressInfo } from 'node:net'
import { tmpdir } from 'node:os'
import { dirname, extname, join, relative, resolve, sep } from 'node:path'
import { firefox, type Browser } from 'playwright'
import { build, type PluginOption } from 'vite'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { pdfjsViewerData } from '../../plugins/vite.js'

const rootDirectory = resolve(import.meta.dirname, '../..')
const distDirectory = join(rootDirectory, 'dist')
const appDirectory = join(rootDirectory, 'tests/fixtures/bundled-app')
const samplePdf = join(rootDirectory, 'tests/fixtures/ccitt-g4.pdf')

const outputDirectories: string[] = []

const listFiles = (directory: string): string[] =>
readdirSync(directory, { withFileTypes: true, recursive: true })
.filter((entry) => entry.isFile())
.map((entry) => relative(directory, join(entry.parentPath, entry.name)).split(sep).join('/'))
.sort()

// Builds the fixture app, which imports the built package the way an installed app does.
const buildApp = async (plugins: PluginOption[], output = {}) => {
const outDir = mkdtempSync(join(tmpdir(), 'pdfjs-viewer-bundled-app-'))
outputDirectories.push(outDir)
await build({
root: appDirectory,
configFile: false,
logLevel: 'error',
plugins,
build: { outDir, emptyOutDir: true, rolldownOptions: { output } }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: The renamed-output case is not portable to Vite 4–7 because those versions ignore build.rolldownOptions. Use the version-neutral rollupOptions setting, or select the appropriate option for each Vite generation, so this test actually covers the supported versions.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/plugin/vite.test.ts, line 34:

<comment>The renamed-output case is not portable to Vite 4–7 because those versions ignore `build.rolldownOptions`. Use the version-neutral `rollupOptions` setting, or select the appropriate option for each Vite generation, so this test actually covers the supported versions.</comment>

<file context>
@@ -0,0 +1,176 @@
+    configFile: false,
+    logLevel: 'error',
+    plugins,
+    build: { outDir, emptyOutDir: true, rolldownOptions: { output } }
+  })
+  copyFileSync(samplePdf, join(outDir, 'ccitt-g4.pdf'))
</file context>
Suggested change
build: { outDir, emptyOutDir: true, rolldownOptions: { output } }
build: { outDir, emptyOutDir: true, rollupOptions: { output } }

})
copyFileSync(samplePdf, join(outDir, 'ccitt-g4.pdf'))
return outDir
}

const findFile = (files: string[], pattern: RegExp) => {
const file = files.find((name) => pattern.test(name))
expect(file, `${pattern} in the build output`).toBeDefined()
return file!
}

const contentTypes: Record<string, string> = {
'.html': 'text/html',
'.js': 'text/javascript',
'.mjs': 'text/javascript',
'.pdf': 'application/pdf',
'.wasm': 'application/wasm'
}

// A dev or preview server answers a missing file with the app's HTML page and a 200. A static host
// answers 404, which is what breaks the viewer in production, so the build output is served that way.
const serve = (directory: string) => new Promise<Server>((done) => {
const server = createServer((request, response) => {
const { pathname } = new URL(request.url ?? '/', 'http://localhost')
const file = join(directory, pathname === '/' ? 'index.html' : decodeURIComponent(pathname))
if (!file.startsWith(directory) || !statSync(file, { throwIfNoEntry: false })?.isFile()) {
response.writeHead(404).end()
return
}
response.writeHead(200, { 'content-type': contentTypes[extname(file)] ?? 'application/octet-stream' })
createReadStream(file).pipe(response)
})
server.listen(0, '127.0.0.1', () => done(server))
})

describe('Vite plugin', () => {
let browser: Browser
let plainOutput: string
let pluginOutput: string

beforeAll(async () => {
browser = await firefox.launch()
plainOutput = await buildApp([])
pluginOutput = await buildApp([pdfjsViewerData()])
})

afterAll(async () => {
await browser?.close()
outputDirectories.forEach((directory) => rmSync(directory, { recursive: true, force: true }))
})

// Opens the built app and reads the first page: the sample PDF fills it with an image that is
// black on the left and white on the right, which PDF.js decodes with `wasm/jbig2.wasm`.
const openApp = async (directory: string) => {
const server = await serve(directory)
const page = await browser.newPage()
const missing: string[] = []
page.on('response', (response) => {
if (response.status() === 404) missing.push(new URL(response.url()).pathname)
})

try {
await page.goto(`http://127.0.0.1:${(server.address() as AddressInfo).port}/`)
// PDF.js finishes the page with or without the image: a failed image is only a warning.
await page.waitForFunction(() => {
const viewer = document.querySelector('pdfjs-viewer-element') as any
return viewer?.iframe?.contentWindow?.PDFViewerApplication?.pdfViewer?.getPageView(0)?.renderingState === 3
})
const colors = await page.evaluate(() => {
const viewer = document.querySelector('pdfjs-viewer-element') as any
const canvas = viewer.iframe.contentDocument.querySelector('.page canvas') as HTMLCanvasElement
const readRed = (x: number) =>
canvas.getContext('2d')!.getImageData(Math.floor(canvas.width * x), Math.floor(canvas.height / 2), 1, 1).data[0]
return { left: readRed(0.25), right: readRed(0.75) }
})
return { ...colors, missing }
} finally {
await page.close()
// The browser keeps its connections open, and `close` alone waits for them to end.
server.closeAllConnections()
await new Promise((done) => server.close(done))
}
}

it('leaves a scanned image blank in a build without the plugin', async () => {
const files = listFiles(plainOutput)
expect(files.filter((file) => file.includes('wasm/'))).toEqual([])

const { left, right, missing } = await openApp(plainOutput)
expect(missing).toContain('/assets/wasm/jbig2.wasm')
expect(left, 'the black half stays blank').toBeGreaterThan(192)
expect(right).toBeGreaterThan(192)
})

it('draws the scanned image in a build with the plugin', async () => {
const { left, right, missing } = await openApp(pluginOutput)
expect(missing.filter((path) => path.startsWith('/assets/'))).toEqual([])
expect(left, 'the black half').toBeLessThan(64)
expect(right, 'the white half').toBeGreaterThan(192)
})

it('emits every data file under its own name next to the runtime file the element resolves it from', () => {
const files = listFiles(pluginOutput)
const viewerDirectory = dirname(findFile(files, /\/viewer-[\w-]+\.mjs$/))
const libDirectory = dirname(findFile(files, /\/pdf-[\w-]+\.mjs$/))

// Every folder in `dist` holds data the element resolves against viewer.mjs, so a folder that
// scripts/copy-worker.mjs starts to ship has to reach the plugin's list too.
const dataFiles = listFiles(distDirectory).filter((file) => file.includes('/'))
expect(dataFiles.length).toBeGreaterThan(200)
const expected = [
...dataFiles.map((file) => [`${viewerDirectory}/${file}`, file]),
[`${libDirectory}/pdf.sandbox.mjs`, 'pdf.sandbox.mjs']
]
for (const [emitted, source] of expected) {
expect(files, source).toContain(emitted)
const sameBytes = readFileSync(join(pluginOutput, emitted)).equals(readFileSync(join(distDirectory, source)))
expect(sameBytes, `${source} is copied byte for byte`).eq(true)
}
expect(files.length).eq(listFiles(plainOutput).length + expected.length)
})

it('follows the runtime files when the app renames and moves them', async () => {
const assetFileNames = ({ names }: { names: string[] }) => {
if (names.includes('viewer.mjs')) return 'static/viewer/v.[hash][extname]'
if (names.includes('pdf.mjs')) return 'static/lib/p.[hash][extname]'
return 'static/[name]-[hash][extname]'
}
const files = listFiles(await buildApp([pdfjsViewerData()], { assetFileNames }))

expect(files).toContain('static/viewer/wasm/jbig2.wasm')
expect(files).toContain('static/viewer/cmaps/Adobe-Japan1-UCS2.bcmap')
expect(files).toContain('static/lib/pdf.sandbox.mjs')
expect(files.filter((file) => file.endsWith('pdf.sandbox.mjs'))).toEqual(['static/lib/pdf.sandbox.mjs'])
expect(files.filter((file) => file.endsWith('jbig2.wasm'))).toEqual(['static/viewer/wasm/jbig2.wasm'])
})

it('is exported from the package as ./vite, with types', () => {
const packageJson = JSON.parse(readFileSync(join(rootDirectory, 'package.json'), 'utf8'))
const require = createRequire(import.meta.url)
expect(require.resolve(`${packageJson.name}/vite`)).eq(join(rootDirectory, 'plugins/vite.js'))
expect(statSync(join(rootDirectory, packageJson.exports['./vite'].types)).isFile()).eq(true)
})
})
4 changes: 3 additions & 1 deletion vite.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/// <reference types="vitest" />
import { readFile } from 'node:fs/promises'
import { resolve } from 'node:path'
import { defineConfig } from 'vitest/config'
import { configDefaults, defineConfig } from 'vitest/config'
import terser from '@rollup/plugin-terser'
import { playwright } from '@vitest/browser-playwright'
import { minify as minifyHtml } from 'html-minifier-terser'
Expand Down Expand Up @@ -96,6 +96,8 @@ export default defineConfig({
copyPublicDir: false
},
test: {
// The plugin tests run in Node, against the built package (vitest.plugin.config.ts).
exclude: [...configDefaults.exclude, 'tests/plugin/**'],
browser: {
// Vitest provider overloads can conflict when multiple provider typings exist in the graph.
provider: playwright(),
Expand Down
12 changes: 12 additions & 0 deletions vitest.plugin.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { defineConfig } from 'vitest/config'

// The plugin tests build a fixture app from the package's `dist` folder and open it in a browser
// they start themselves, so they run in Node, after the package is built. The element's own tests
// run in the browser (vite.config.ts).
export default defineConfig({
test: {
include: ['tests/plugin/**/*.test.ts'],
testTimeout: 60_000,
hookTimeout: 60_000
}
})
Loading