Skip to content

feat(dicomImageLoader): add wasmBasePath option for codec binaries - #2826

Open
wayfarer3130 wants to merge 3 commits into
mainfrom
feat/wasm-base-path
Open

feat(dicomImageLoader): add wasmBasePath option for codec binaries#2826
wayfarer3130 wants to merge 3 commits into
mainfrom
feat/wasm-base-path

Conversation

@wayfarer3130

@wayfarer3130 wayfarer3130 commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator

Each decoder locates its WASM binary with a bare @cornerstonejs/codec-... specifier inside new URL(..., import.meta.url). Bundlers do not rewrite bare specifiers there, so bundled applications get a request for a path that does not exist - typically answered by the SPA fallback, surfacing as:

CompileError: WebAssembly.instantiate(): expected magic word 00 61 73 6d,
found 3c 21 64 6f (3c 21 64 6f is "<!do")

The only fix available to consumers today is to post-process the built worker and rewrite those specifiers, which every bundler-based integration has to reinvent and which breaks silently whenever the decoders change.

Add a single wasmBasePath loader option instead:

dicomImageLoaderInit({ wasmBasePath: '/assets/cs-wasm/' })

One root for all four codecs - deliberately no per-codec paths. The directory holds the binaries under their published file names. A relative path resolves against the decode worker's location; absolute paths and full URLs (e.g. a CDN) are used as given. When unset, the existing import.meta.url resolution applies, so unbundled and script-tag usage is unaffected.

The value reaches the decoders through the per-task decode config, and is applied before any codec initializes.

Also documents the option and replaces the docs reference to setConfiguration({ wasmBasePath }), which was never implemented.

Summary by CodeRabbit

  • New Features

    • Added configurable wasmBasePath to control where codec decoder WASM binaries are loaded from.
    • Forwarded the setting through the decode flow so it applies consistently across supported JPEG, JPEG-LS, and HTJ2K decoders.
  • Bug Fixes

    • Improved WASM URL/base-path resolution to better handle unset values, absolute/relative paths, and missing trailing slashes.
  • Documentation

    • Updated framework setup guidance (Vue/React/Vite and Angular) with clearer codec WASM hosting and wasmBasePath configuration.
  • Tests

    • Added unit tests covering default behavior and multiple resolution scenarios.

Each decoder locates its WASM binary with a bare `@cornerstonejs/codec-...`
specifier inside `new URL(..., import.meta.url)`. Bundlers do not rewrite bare
specifiers there, so bundled applications get a request for a path that does
not exist - typically answered by the SPA fallback, surfacing as:

  CompileError: WebAssembly.instantiate(): expected magic word 00 61 73 6d,
  found 3c 21 64 6f            (3c 21 64 6f is "<!do")

The only fix available to consumers today is to post-process the built worker
and rewrite those specifiers, which every bundler-based integration has to
reinvent and which breaks silently whenever the decoders change.

Add a single `wasmBasePath` loader option instead:

  dicomImageLoaderInit({ wasmBasePath: '/assets/cs-wasm/' })

One root for all four codecs - deliberately no per-codec paths. The directory
holds the binaries under their published file names. A relative path resolves
against the decode worker's location; absolute paths and full URLs (e.g. a CDN)
are used as given. When unset, the existing import.meta.url resolution applies,
so unbundled and script-tag usage is unaffected.

The value reaches the decoders through the per-task decode config, and is
applied before any codec initializes.

Also documents the option and replaces the docs reference to
`setConfiguration({ wasmBasePath })`, which was never implemented.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Claude Code Review

Claude Code Review is paused for this repository. To reconnect it, an admin of this repository's GitHub organization (or the account owner, for personal repositories) who can also manage your Claude organization's Code Review settings needs to re-link GitHub in Code Review settings. This is a one-time step.

Tip: disable this comment in your organization's Code Review settings.

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 1dec1a4c-5833-4e7c-9fc0-2114dfd5472c

📥 Commits

Reviewing files that changed from the base of the PR and between 6c8b668 and 8007590.

📒 Files selected for processing (2)
  • packages/dicomImageLoader/src/decodeImageFrameWorker.js
  • packages/docs/docs/getting-started/vue-angular-react-vite.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/docs/docs/getting-started/vue-angular-react-vite.md

📝 Walkthrough

Walkthrough

Adds configurable codec WASM base-path support, forwards the option to decode workers, applies shared URL resolution across codec decoders, and documents deployment setup and required binary filenames.

Changes

Configurable codec WASM paths

Layer / File(s) Summary
WASM base-path contract and resolution
packages/dicomImageLoader/src/shared/wasmBasePath.ts, packages/dicomImageLoader/src/types/*, packages/dicomImageLoader/src/__tests__/wasmBasePath.spec.ts
Adds shared base-path state, URL resolution, loader and worker configuration fields, and tests for default, absolute, relative, URL, and configured-path behavior.
Decode configuration forwarding
packages/dicomImageLoader/src/imageLoader/createImage.ts, packages/dicomImageLoader/src/decodeImageFrameWorker.js
Forwards wasmBasePath into decode configuration and initializes it before decoder selection.
Codec WASM resolution
packages/dicomImageLoader/src/shared/decoders/*
Configures WASM paths during codec initialization and resolves codec-specific filenames through the shared resolver.
Deployment guidance
packages/docs/docs/getting-started/vue-angular-react-vite.md
Documents bundler-specific codec binary handling, hosted binaries, initialization with wasmBasePath, required filenames, and subpath deployment handling.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Loader as createImage
  participant Worker as decodeImageFrame
  participant Decoder as Codec initializer
  participant Resolver as resolveWasmUrl
  Loader->>Worker: pass wasmBasePath in decodeConfig
  Worker->>Decoder: initialize decoder
  Decoder->>Resolver: resolve codec WASM filename
  Resolver-->>Decoder: return WASM URL
Loading

Suggested reviewers: jbocce

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change, but it does not follow the required template sections or include checklist/testing details. Reformat the PR description to include Context, Changes & Results, Testing, and Checklist sections, and mark the required checkboxes.
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise, accurate, and follows the repo's semantic-release format for the main change.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/wasm-base-path

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/dicomImageLoader/src/decodeImageFrameWorker.js`:
- Around line 367-369: Update the decode-task setup around
setWasmBasePathFromConfig so each task explicitly resets the WASM base path when
decodeConfig does not provide one, while preserving configured paths when
present. Ensure a later unconfigured task falls back to the codec’s built-in URL
instead of inheriting state from an earlier task.

In `@packages/docs/docs/getting-started/vue-angular-react-vite.md`:
- Line 104: Update the diagnostic code fence in vue-angular-react-vite.md to
include an explicit language identifier, such as text, immediately after the
opening fence.
- Line 80: Update the Vue subpath setup bullet in vue-angular-react-vite.md to
include the same codec WASM guidance as the React entry: link to “Codec WASM
location” and mention configuring init({ wasmBasePath }) when serving codec
binaries yourself.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 93ec5169-8bd3-4c90-ab54-bd58108b2b18

📥 Commits

Reviewing files that changed from the base of the PR and between a35a2b5 and 6c8b668.

📒 Files selected for processing (12)
  • packages/dicomImageLoader/src/__tests__/wasmBasePath.spec.ts
  • packages/dicomImageLoader/src/decodeImageFrameWorker.js
  • packages/dicomImageLoader/src/imageLoader/createImage.ts
  • packages/dicomImageLoader/src/shared/decoders/decodeHTJ2K.ts
  • packages/dicomImageLoader/src/shared/decoders/decodeJPEG2000.ts
  • packages/dicomImageLoader/src/shared/decoders/decodeJPEGBaseline8Bit.ts
  • packages/dicomImageLoader/src/shared/decoders/decodeJPEGLS.ts
  • packages/dicomImageLoader/src/shared/wasmBasePath.ts
  • packages/dicomImageLoader/src/types/LoaderDecodeOptions.ts
  • packages/dicomImageLoader/src/types/LoaderOptions.ts
  • packages/dicomImageLoader/src/types/WebWorkerTypes.ts
  • packages/docs/docs/getting-started/vue-angular-react-vite.md

Comment thread packages/dicomImageLoader/src/decodeImageFrameWorker.js
Comment thread packages/docs/docs/getting-started/vue-angular-react-vite.md Outdated
Comment thread packages/docs/docs/getting-started/vue-angular-react-vite.md
@wayfarer3130
wayfarer3130 requested a review from jbocce July 30, 2026 11:56
A decodeConfig without wasmBasePath leaves the current value in place instead of
clearing it, which reads like leaked state across decode tasks. It is load
bearing: every decoder calls its own initialize()/initLibjpegTurbo() with no
arguments from decodeAsync, so a reset on undefined would clear the path between
the task setup and the codec's first locateFile call - reintroducing the bare
specifier 404 the option exists to fix.

Behavior and tests unchanged; the invariant was only documented on the setter.
The Codec WASM location section claimed bundlers do not rewrite bare specifiers
inside new URL(). That is only true of esbuild. Verified against the pattern the
decoders use:

  webpack 5.105.0  resolves it via the package exports map, emits the asset
  Vite 8.1.5       resolves it, emits the asset (inlines under the size limit)
  esbuild 0.24.2   passes it through unchanged
  esbuild 0.28.1   passes it through unchanged

So Angular's esbuild-based application builder is the case that needs
wasmBasePath, while the Vite templates work without it. State the per-bundler
behavior, note that Vite's dev prebundling runs esbuild (which is what the
existing optimizeDeps.exclude guidance is for), and give Vue/React a short
pointer framed as optional - serving the binaries from a chosen location such as
a CDN - rather than as required setup.
@wayfarer3130

Copy link
Copy Markdown
Collaborator Author

There was an earlier change that was much more extensive than this one: #1982
This work is much simpler, just adding the base path. The full ability to customize the load paths should be done along side a standardization of the wasm codecs.

wayfarer3130 added a commit to cornerstonejs/angular-cornerstone3d that referenced this pull request Jul 30, 2026
The DICOM image loader's decoders locate their WASM binaries with a bare
@cornerstonejs/codec-... specifier inside new URL(..., import.meta.url).
Angular's application builder is esbuild-based, and esbuild passes those
specifiers through unchanged (verified on 0.24.2 and 0.28.1; webpack 5 and Vite
both resolve them), so the request 404s, the SPA fallback HTML reaches the
decoder, and decoding dies with "expected magic word 00 61 73 6d, found 3c 21
64 6f".

scripts/bundle-dicom-worker.js used to rewrite those four specifiers inside the
bundled worker. Replace that with the loader's wasmBasePath option, a single
root for every codec:

  dicomImageLoaderInit({ maxWebWorkers: 1, wasmBasePath })

It resolves against document.baseURI, so one build works at the site root and
under /subpath/. The codec binaries now land in one flat directory,
public/cs-dicom-loader/wasm/, matching the option's contract. The bundling
script keeps a build-time check that warns - rather than fails, so pnpm install
can still complete - when the installed loader has no wasmBasePath support.

wasmBasePath is not in a Cornerstone3D release yet; see
cornerstonejs/cornerstone3D#2826. scripts/link-cs3d.js points the app at a local
Cornerstone3D build until it ships (pnpm link:cs3d, link:cs3d:status,
unlink:cs3d). It copies each package's dist rather than symlinking: a symlinked
dist makes the bundler resolve the loader's own dependencies out of the
Cornerstone3D checkout, where this app's Node built-in stubs do not exist, and
the build fails with Could not resolve "fs".

Verified against the local build with the rewrite removed - dev, dev:subpath,
preview and preview:subpath each render the CT volume, 135/135 frames decoded,
codec wasm 200, no console errors.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant