Repository navigation
feat: Vite plugin that emits the PDF.js data next to the bundled viewer #84
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 })) | ||
|
|
||
| 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) | ||
| }) | ||
| }) | ||
| }) | ||
| } | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 not shown.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 } } | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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 Prompt for AI agents
Suggested change
|
||||||
| }) | ||||||
| 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) | ||||||
| }) | ||||||
| }) | ||||||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } | ||
| }) |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P3:
anchorsreads bothdistanchor 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 whendistis absent.Prompt for AI agents