Skip to content

Bundler plugin that emits the PDF.js data folders next to the bundled viewer #83

Todo

Description

@alekswebnet

Follow-up to #66, which kept the PDF.js data folders (wasm/, cmaps/, standard_fonts/, iccs/, images/, pdf.sandbox.mjs) a documented requirement: copy dist and set assets-base. This proposes a build plugin that removes the copy step for bundled apps and keeps the folder-based loading PDF.js expects. ICC, the scripting sandbox and the annotation icons are covered too, which the BinaryDataFactory route in #66 could not do. The element needs no change.

Why

Seen in a production app built with Vite: scanned PDFs lost their black text. The text layer of a scan is usually a JBIG2 image, assets/wasm/jbig2.wasm returned 404, and only the color parts of the page rendered. The only trace is three PDF.js warnings in the console:

Warning: #getWasmInstance: Error: Failed to fetch file ".../assets/wasm/jbig2.wasm" with "".
Warning: #getJsInstance: TypeError: Failed to fetch dynamically imported module: .../assets/wasm/jbig2_nowasm_fallback.js
Warning: Unable to decode image "img_p1_1": "Jbig2Error: JBig2 failed to initialize".

It works in vite dev and in Storybook (the dev server serves the real dist), and breaks after vite build, so it reaches production unnoticed. The README's copy + assets-base fixes it, but every app has to find that paragraph and add a copy step, and the runtime files the bundler emitted then go unused.

Idea

The element derives every data location from a file the bundler emits: new URL('wasm/', viewerSrc) and new URL('pdf.sandbox.mjs', pdfjsLibSrc) (pdfjs-viewer-element.ts:69-76). Bundlers emit viewer.mjs and pdf.mjs and nothing else. The plugin does two things:

  1. Puts the two anchors in a hashed folder of their own. It wraps assetFileNames for those two files only, so assets/[name]-[hash].[ext] becomes assets/[name]-[hash]/[name][extname]: assets/viewer-DfOqdCoM/viewer.mjs, assets/pdf-CSmHxz2q/pdf.mjs.
  2. Writes the data next to each anchor under its real name: assets/viewer-DfOqdCoM/wasm/jbig2.wasm, assets/pdf-CSmHxz2q/pdf.sandbox.mjs.

The element's defaults then resolve as they are, and the data always comes from the installed version.

Why the hashed folder: hosts often cache all of /assets/ as immutable, because everything Vite writes there is hashed. Fixed names such as assets/wasm/jbig2.wasm would break that assumption: after an upgrade a browser could keep the old jbig2.wasm or quickjs-eval.js and pair it with the new worker, which is the same silent breakage again. viewer.mjs and pdf.mjs both carry the PDF.js version ("6.5.438"), and all the data comes from PDF.js, so every PDF.js release changes their hash and with it the folder.

Sketch (Vite)

Tested as below. Inside the package distDirectory would not be an option: the plugin knows where it lives. Every data folder in dist is flat, so one readdirSync level is enough.

import { readdirSync, readFileSync, statSync } from 'node:fs'
import { basename, dirname, join, posix, resolve } from 'node:path'

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

const extensionPattern = /(\[extname\]|\.\[ext\])$/

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

const getHashedDirectoryPattern = (pattern) =>
  (extensionPattern.test(pattern)
    ? pattern.replace(extensionPattern, '/[name][extname]')
    : pattern)

export const pdfjsViewerData = ({ distDirectory }) => {
  let root = process.cwd()

  const getDataEntryList = (asset) => {
    const sourcePath = asset.originalFileNames
      ?.map((name) => resolve(root, name))
      .find((path) => dirname(path) === resolve(distDirectory))
    return sourcePath && dataByAnchor[basename(sourcePath)]
  }

  return {
    name: 'pdfjs-viewer-data',
    apply: 'build',
    configResolved(config) {
      root = config.root
    },
    outputOptions(outputOptions) {
      const { assetFileNames = 'assets/[name]-[hash][extname]' } = outputOptions
      return {
        ...outputOptions,
        assetFileNames: (asset) => {
          const pattern = (typeof assetFileNames === 'function' ? assetFileNames(asset) : assetFileNames)
          return (getDataEntryList(asset) ? getHashedDirectoryPattern(pattern) : pattern)
        },
      }
    },
    generateBundle(_options, bundle) {
      Object.values(bundle)
        .filter((output) => output.type === 'asset')
        .forEach((asset) => {
          const entryList = getDataEntryList(asset)
          if (!entryList) return

          const outputDirectory = posix.dirname(asset.fileName)
          entryList
            .flatMap((entry) => listFiles(distDirectory, entry))
            .forEach((file) => {
              this.emitFile({
                type: 'asset',
                fileName: posix.join(outputDirectory, file),
                source: readFileSync(join(distDirectory, file)),
              })
            })
        })
    },
  }
}

What the app would write:

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

export default { plugins: [pdfjsViewerData()] }

The anchors are matched by their source path, not by name, and the wrapper keeps the app's own assetFileNames (string or function) for everything else. Vite 8's default is assets/[name]-[hash].[ext], hence both suffixes in extensionPattern. A custom pattern that ends in neither keeps the flat layout, and with it the cache problem; the plugin could warn in that case.

Results

Vite 8.3.8, 4.5.0 from npm, a minimal app that only imports the element, headless Chromium, jbig2_symbol_offset.pdf from the PDF.js test files:

vite build vite build + plugin
jbig2.wasm 404 at assets/wasm/, and 404 for jbig2_nowasm_fallback.js 200 at assets/viewer-DfOqdCoM/wasm/, body starts with \0asm
Console the three warnings above none
Dark pixels on page 1 0 % 0.98 %

The plugin adds 286 files, about 4.3 MB, to the build output: wasm 1.4 MB, cmaps 1.6 MB, standard_fonts 0.8 MB, images 0.3 MB, pdf.sandbox.mjs 0.1 MB, iccs 20 KB. They are only fetched when a document needs them, so everything is emitted by default; an include option only if someone asks for it.

Not tested: CMaps, standard fonts, ICC, the sandbox and the icons in a document (they resolve from the same folder, so they should behave like wasm/, but no test file exercised them), Rollup and Rolldown on their own, webpack and Rspack, SSR builds.

Coverage by bundler

  • Vite, Rollup, Rolldown: the outputOptions and generateBundle hooks above. Outside Vite there is no configResolved: resolve() keeps an absolute originalFileNames entry as it is and resolves a relative one against the working directory. Plain Rollup also needs a plugin that emits new URL('./x', import.meta.url) files in the first place. Unverified.
  • webpack 5, Rspack: the same idea in compilation.hooks.processAssets: find the assets whose info.sourceFilename is the package's viewer.mjs or pdf.mjs, then compilation.emitAsset the data next to them. The hashed folder needs its own naming hook there. unplugin could ship both from one source, although the asset hooks are bundler-specific either way.
  • Turbopack (the Next.js 16 default): it runs webpack loaders, not plugins, so there is nothing to hook into. Copy + assets-base stays the documented route there, and for builds without a bundler.

Loud failure (ship first)

Independent of the plugin, and it also helps Turbopack users and builds without a bundler: when the worker URL looks moved by a bundler (a hashed pdf.worker.min-*.mjs), probe wasm-url once and console.error a link to the hosting docs if the data is missing. Check the body, not the status: vite preview and SPA hosts answer a missing .wasm with index.html and a 200, so test for the \0asm header (or at least the content type). The same applies to the fixture test.

Packaging

  • files only lists dist and types, so the ./vite entry needs its own Node-only file and types outside the browser build, plus the exports entry.
  • The comment at pdfjs-viewer-element.ts:62-65 ("bundlers emit… not these folders") needs updating.

Proposed steps

  • The missing-data error, with the \0asm check
  • Ship the plugin as @missing-elements/pdfjs-viewer/vite (own file, types, files and exports entries)
  • Fixture build + browser test with the PDF.js JBIG2, CCITT, JPX and CMap test files, checking bodies rather than statuses
  • webpack / Rspack variant
  • README and hosting docs: the plugin for Vite and webpack; copy + assets-base for Turbopack and builds without a bundler; the comment at pdfjs-viewer-element.ts:62-65

Metadata

Metadata

Assignees

Labels

enhancement

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions