# DICOM Viewer: Local Library Bundling

**Date**: 2025-01-12  
**Status**: **REQUIRED** - CDN approach doesn't work in MV3  
**Priority**: **HIGH** - Viewer won't function without local bundling  
**Related**: `DICOM_VIEWER_IMPLEMENTATION.md`

## ⚠️ Critical: CDN Approach Doesn't Work

**Chrome MV3 blocks external scripts in extension pages.** The CDN-based implementation in `viewer.html` will not work because:

- Extension pages cannot load external scripts (blocked by browser security)
- CSP cannot allow external URLs for `extension_pages` 
- CDN scripts will fail to load

**This bundling is REQUIRED, not optional.** The viewer will not function until libraries are bundled locally.

## Overview

Currently, the DICOM viewer loads Cornerstone.js and related libraries from CDN (jsDelivr). For production use, these libraries should be bundled locally to:

1. **Remove internet dependency** - Viewer works offline
2. **Improve performance** - No CDN latency
3. **Ensure version stability** - CDN versions could change
4. **Security** - No external script dependencies
5. **Compliance** - Some environments restrict external scripts

## Current Implementation

The viewer loads libraries via CDN in `src/viewers/dicom/viewer.html`:

```html
<script src="https://cdn.jsdelivr.net/npm/dicom-parser@1.8.28/dist/dicomParser.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/cornerstone-core@2.6.1/dist/cornerstone.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/cornerstone-wado-image-loader@4.9.1/dist/cornerstoneWADOImageLoader.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/cornerstone-math@0.1.9/dist/cornerstoneMath.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/cornerstone-tools@6.0.7/dist/cornerstoneTools.min.js"></script>
```

## Required Libraries

### Core Libraries
- `dicom-parser@1.8.28` - DICOM file parsing
- `cornerstone-core@2.6.1` - Core rendering engine
- `cornerstone-wado-image-loader@4.9.1` - DICOM image loading
- `cornerstone-math@0.1.9` - Mathematical utilities
- `cornerstone-tools@6.0.7` - Interactive tools

### Additional Dependencies
- WebAssembly codecs (for JPEG 2000, etc.) - loaded dynamically by cornerstone-wado-image-loader
- Web Workers - cornerstone-wado-image-loader uses web workers

## Implementation Options

### Option 1: Download and Bundle Manually (Recommended)

**Steps:**

1. **Install via npm** (for version management):
   ```bash
   npm install dicom-parser@1.8.28
   npm install cornerstone-core@2.6.1
   npm install cornerstone-wado-image-loader@4.9.1
   npm install cornerstone-math@0.1.9
   npm install cornerstone-tools@6.0.7
   ```

2. **Copy library files to extension**:
   ```
   filevine-plugin/
   ├── src/
   │   └── viewers/
   │       └── dicom/
   │           ├── viewer.html
   │           └── lib/
   │               ├── dicomParser.min.js
   │               ├── cornerstone.min.js
   │               ├── cornerstoneWADOImageLoader.min.js
   │               ├── cornerstoneMath.min.js
   │               └── cornerstoneTools.min.js
   ```

3. **Update viewer.html** to use local paths:
   ```html
   <script src="lib/dicomParser.min.js"></script>
   <script src="lib/cornerstone.min.js"></script>
   <script src="lib/cornerstoneWADOImageLoader.min.js"></script>
   <script src="lib/cornerstoneMath.min.js"></script>
   <script src="lib/cornerstoneTools.min.js"></script>
   ```

4. **Handle WebAssembly codecs**:
   - Copy codec files from `node_modules/cornerstone-wado-image-loader/dist/codecs/`
   - Update codec path in viewer initialization:
   ```javascript
   const codecPath = chrome.runtime.getURL('src/viewers/dicom/lib/codecs/');
   cornerstoneWADOImageLoader.webWorkerManager.codecPath = codecPath;
   ```

5. **Handle Web Workers**:
   - Copy worker file: `cornerstoneWADOImageLoaderWebWorker.js`
   - Update worker path:
   ```javascript
   cornerstoneWADOImageLoader.webWorkerManager.workerPath = 
     chrome.runtime.getURL('src/viewers/dicom/lib/cornerstoneWADOImageLoaderWebWorker.js');
   ```

6. **Update manifest.json**:
   - Add lib directory to `web_accessible_resources`:
   ```json
   "web_accessible_resources": [
     {
       "resources": [
         "src/viewers/*",
         "src/viewers/dicom/lib/*",
         "src/content/interception.js",
         "src/lib/*.js"
       ],
       "matches": ["https://*.filevineapp.com/*"]
     }
   ]
   ```

7. **Remove CSP for CDN** (if no longer needed):
   ```json
   "content_security_policy": {
     "extension_pages": "script-src 'self'; object-src 'self'"
   }
   ```

### Option 2: Build Script with Copy

Create a build script (`scripts/copy-dicom-libs.js`) to automate copying:

```javascript
const fs = require('fs');
const path = require('path');

const libs = [
  'dicom-parser/dist/dicomParser.min.js',
  'cornerstone-core/dist/cornerstone.min.js',
  'cornerstone-wado-image-loader/dist/cornerstoneWADOImageLoader.min.js',
  'cornerstone-math/dist/cornerstoneMath.min.js',
  'cornerstone-tools/dist/cornerstoneTools.min.js'
];

const codecs = [
  'cornerstone-wado-image-loader/dist/codecs/*'
];

const workers = [
  'cornerstone-wado-image-loader/dist/cornerstoneWADOImageLoaderWebWorker.js'
];

// Copy files to src/viewers/dicom/lib/
// Implementation details...
```

### Option 3: Bundle with Webpack/Rollup

Create a bundled version that includes all dependencies:

**Pros:**
- Single file to load
- Tree-shaking removes unused code
- Optimized bundle size

**Cons:**
- More complex build setup
- May need to handle WebAssembly separately
- Cornerstone tools may not bundle well

## File Structure After Bundling

```
filevine-plugin/
├── src/
│   └── viewers/
│       └── dicom/
│           ├── viewer.html
│           └── lib/
│               ├── dicomParser.min.js
│               ├── cornerstone.min.js
│               ├── cornerstoneWADOImageLoader.min.js
│               ├── cornerstoneMath.min.js
│               ├── cornerstoneTools.min.js
│               ├── cornerstoneWADOImageLoaderWebWorker.js
│               └── codecs/
│                   ├── charls.js
│                   ├── openjpeg.js
│                   └── ... (other codec files)
├── package.json (with dependencies)
└── scripts/
    └── copy-dicom-libs.js (optional build script)
```

## Testing Checklist

After bundling, verify:

- [ ] Viewer loads without internet connection
- [ ] All libraries load correctly (check Network tab)
- [ ] DICOM files render correctly
- [ ] Web Workers initialize (check Console)
- [ ] Codecs load for JPEG 2000 files
- [ ] All tools work (zoom, pan, window/level, rotate)
- [ ] No CSP violations in console
- [ ] Extension size is acceptable (libraries add ~2-3MB)

## Size Considerations

Approximate library sizes:
- `dicom-parser.min.js` - ~150KB
- `cornerstone.min.js` - ~200KB
- `cornerstoneWADOImageLoader.min.js` - ~300KB
- `cornerstoneMath.min.js` - ~50KB
- `cornerstoneTools.min.js` - ~400KB
- Codecs - ~500KB total
- **Total**: ~1.6MB (minified)

## Migration Steps

1. **Create lib directory structure**
2. **Download/copy library files**
3. **Update viewer.html script tags**
4. **Update codec/worker paths in JavaScript**
5. **Update manifest.json**
6. **Test thoroughly**
7. **Remove CDN CSP if no longer needed**
8. **Update documentation**

## Rollback Plan

If bundling causes issues:

1. Revert to CDN URLs in viewer.html
2. Restore CDN CSP in manifest.json
3. Test CDN version still works
4. Document issues encountered

## Notes

- **WebAssembly codecs** are loaded dynamically - ensure paths are correct
- **Web Workers** must be in web_accessible_resources
- **Version pinning** - Use exact versions to avoid breaking changes
- **License compliance** - Cornerstone.js uses MIT license (compatible)

## Related Files

- `src/viewers/dicom/viewer.html` - Main viewer (needs script tag updates)
- `manifest.json` - Needs web_accessible_resources and CSP updates
- `package.json` - Add dependencies if using npm
- `DICOM_VIEWER_IMPLEMENTATION.md` - Current implementation docs

## References

- [Cornerstone.js GitHub](https://github.com/cornerstonejs/cornerstone)
- [Cornerstone Tools GitHub](https://github.com/cornerstonejs/cornerstoneTools)
- [Chrome Extension Web Accessible Resources](https://developer.chrome.com/docs/extensions/mv3/manifest/web_accessible_resources/)
