Repository navigation
feat: @dcmjs-org/encapsulated — encapsulated PDF wrap and unwrap - #577
Conversation
The package manifest (publishable under the @dcmjs-org scope, main at src/index.js, repository directory set), a short README, and the lockfile entry linking the one dependency, @dcmjs-org/core. Co-Authored-By: Claude Fable 5 <[email protected]>
A verbatim port of src/encapsulated/encapsulatedPdf.js from the v2 branch
HEAD (including the { InlineBinary } unwrap that postdates the PR #512
review), with its core import rebased onto @dcmjs-org/core and the PDF half
of the encapsulated index as the package surface. The video half stays on
the v2 branch for the media wave.
The eight-test v2 suite comes along, reworked for this branch's engine: the
legacy datasetToBuffer / DicomMessage.readFile round-trip becomes
denaturalize -> fromDataSet -> Part10Writer -> fromPart10 ->
NaturalizedListener, and the last test's read of test/sample-dicom.dcm
(provenance still being traced) is replaced by a synthetic MR instance
round-tripped through the same pipeline, so neither the package nor its
suite touches @dcmjs-org/legacy or the fixture.
Co-Authored-By: Claude Fable 5 <[email protected]>
…ding 16) The pad-trim heuristic strips a real zero byte: the Part 10 writer pads only an odd-length OB value, so a stored even length is ambiguous — the old code trimmed a trailing 0x00 anyway, corrupting an even-length original that genuinely ends in a zero byte (a 10-byte payload ending 0x00 came back as 9 bytes). encapsulatePdf now records EncapsulatedDocumentLength (0042,0015) with the exact original length, and extractEncapsulatedPdf slices to the declared length when present, keeping the trailing-NUL heuristic only as the fallback for files written before the element existed. The four new tests were written first and observed failing against the ported-unfixed code: the even-length zero-tail round-trip (9 bytes back, red), the recorded length element, and the declared-length odd slice; the heuristic-fallback test passed before and after, pinning that files without 0042,0015 still extract exactly. Co-Authored-By: Claude Fable 5 <[email protected]>
feat(pdfs): the @dcmjs-org/pdfs package — encapsulated PDF wrap and unwrap
…ented GHSA-vfj7-8cjw-p6xm was published 2026-10-02 with a claimed fix range of >=3.0.4, but no such braces release exists on the registry, so there is nothing to override to. Every path is dev tooling; braces never reaches the published packages. Same entry the fhir staging branch already carries (#589) — remove it the moment a patched braces ships. Co-Authored-By: Claude Fable 5 <[email protected]> (cherry picked from commit 7261970)
Per review on #542: the guide existed to hold the staged-landing PR descriptions to one standard, and every description is now written. Removed rather than kept stale; git history preserves it if the team wants it back later. The PR template keeps the one-line spirit of it. Co-Authored-By: Claude Fable 5 <[email protected]> (cherry picked from commit 2a5935e)
…pdfs # Conflicts: # pnpm-lock.yaml # pnpm-workspace.yaml
wayfarer3130
left a comment
There was a problem hiding this comment.
Change the name of hte overall package to @dcmjs-org/encapsulated as this is general encapsulation support.
Then, somewhere near core have a set of methods/helpers that know how to extract various parts of a naturalized instance or a part 10 data set. That way you can just create a fractional naturalized encapsulated pdf that has all the defaults for things, and you just do additional Object.assign(result, naturalizedInstance)
What that gives you is the ability to extend an existing series by passing in the series information, drop the value into a specific instance uid, change other study information not already listed.
If the default pdf encapsulated object then gets replaced (can have a "set default" method), someone can create new options for what is included.
…ated; add sourceInstance compose path Addresses review on PR #577: - Rename the package to @dcmjs-org/encapsulated: it is the home for DICOM's encapsulated-document IODs, with PDF the first to land (CDA/STL/OBJ/MTL to follow). Video stays in @dcmjs-org/video — it is encapsulated pixel data, not a document. Updates package name/description, headers, README, and the RELEASE_PLAN table. - Add an additive options.sourceInstance path to encapsulatePdf: copy the Patient and General Study context off a naturalized instance (or the first of an array) instead of retyping it. Precedence is defaults < sourceInstance < explicit options; the document's own identity (SOP class, Modality, SOP/Series UIDs) is never inherited, so the report lands as a new series within the source study. De-novo stays the default. - 7 new tests cover the compose path (19 in the package suite). The generic module-extraction helper this hand-rolls belongs near core and is tracked separately in #612. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Worked through the review: Renamed the package to Added the compose-from-instance path you described. Rather than a literal On "helpers near core that extract parts of a naturalized or Part 10 instance": agreed it's useful, but it reads as a core/parser-level primitive (pull the patient module, study module, etc. out of any instance) rather than something that should live in this package — I'd rather not grow the encapsulated package's surface into that. Filed as #612; when it lands, On a pluggable "set default" method: held off for now — easy to add once there's a second encapsulated type here to share defaults with, but with only PDF today it'd be a config surface with a single caller. Happy to add it when CDA or STL lands. |
…pdfs # Conflicts: # pnpm-lock.yaml
…helpers Addresses the PR #577 review / follow-up conversation with Bill, and closes #612. Core (@dcmjs-org/core): - Add utilities/copyAttributesByLevel.js: patientTags / studyTags / seriesTags / patientStudyTags as Sets (names + coverage mirror cornerstone3D's copyStudyTags.ts for portability), plus copyAttributesByLevel(source, dataLevel) which copies the attributes at or above a level (patient flows down to study / series / instance). Present + non-empty only; _meta/_vrMap not copied. - Export them from the core index. Encapsulated (@dcmjs-org/encapsulated): - Add encapsulate(bytes, options): the generic Encapsulated Document builder. Layered merge defaults < baseDicom < inherited < explicit overrides, then the document payload/encoding pinned on top. Identity guard: SOPClassUID / SOPInstanceUID / SeriesInstanceUID / Modality are never inherited, so a document can't impersonate the source even at series/instance level. A fluent chaining builder is noted as a deferred follow-up. - Add defaults/pdfBase.js: the PDF-identifying base defaults (factory). - encapsulatePdf is now a thin decorator over encapsulate: magic-check, then supply the PDF base + mime type. New instance + dataLevel options; sourceInstance kept as a back-compat alias (maps to instance, dataLevel 'study'). extractEncapsulatedPdf unchanged (finding-16 behavior preserved). - README + public exports updated. Tests: 10 new core tests, 8 new encapsulate tests; the 19 existing encapsulated tests stay green. Full suite 951 passed / 12 skipped / 0 failed. Co-Authored-By: Claude Fable 5 <[email protected]>
|
Restructured per the conversation:
18 new tests; the 19 existing encapsulated tests stay green; full suite 951 passed / 0 failed. |
| ContentDate: date, | ||
| ContentTime: time, | ||
| AcquisitionDateTime: DicomMetaDictionary.dateTime(), | ||
| ReferringPhysicianName: "", |
There was a problem hiding this comment.
These fixed values should come in the default base object.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ses it Core (@dcmjs-org/core): - createInstance({ baseDicom, instance, dataLevel, levels, predecessor, ...overrides }): merge base < inherited < overrides. Logs a warning when an inherited Modality or SOPClassUID differs from the base. - Base blocks are objects, functions of a context, arrays, or combineBases(...items); a combined block keeps its parts on .items. Core blocks: patientBase, studyBase, seriesBase, instanceBase, equipmentBase (defaultInstanceBase), plus predecessorBase and nextSeriesNumberBase(seriesList, filter). - The level blocks create new identity only below dataLevel, so dataLevel "series" now joins the source series. The "instance" level is removed; instance values are overrides. - DATA_LEVELS is a list of { name, tags }; extendDataLevels adds tags and a custom list goes in the levels option. PatientAge, PatientSize and PatientWeight are study-level. - deepCloneInstance clones naturalized data, wraps functions, clones promise values, and shares binary unless copyBinary is set. Nothing is frozen. - hierarchicalReferences builds Hierarchical SOP Instance References; predecessorBase uses it for PredecessorDocumentsSequence. Encapsulated (@dcmjs-org/encapsulated): - encapsulate calls createInstance; the bases are compositions: encapsulatedBase = defaultInstanceBase + encapsulatedDocumentBase + predecessorBase, encapsulatedPdfBase adds pdfBase. - MIME type precedence: mimeType > dataset value > base. - The sourceInstance alias and NON_INHERITABLE are removed. - The README splits user and implementation requirements. Tests: the core suites own the level rules; low-value and duplicate tests are removed; the encapsulated suites share test/part10Helpers.js. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…media 1.0-beta now has #577 (@dcmjs-org/encapsulated) and #585 (@dcmjs-org/video and @dcmjs-org/imaging, built on createInstance). The merge takes the video package from 1.0-beta and moves the media wave onto the new packages: - remove packages/pdfs; @dcmjs-org/encapsulated replaces it - the media bundle and the DicomEventStream factories import from @dcmjs-org/encapsulated, @dcmjs-org/imaging, and @dcmjs-org/video - the bundle re-exports the base blocks and the generic encapsulate, and drops normalizeFragmentBytes, which the video package no longer exports - the factories pass the createInstance options to the builders; the DICOM attributes go in `overrides`, and the tests use that form - a new test checks that fromPdf passes instance and dataLevel through Co-Authored-By: Claude Opus 5.5 <[email protected]>
Take the 1.0-beta design for every package that the assemblies #577, #585, #588 and #584 merged: @dcmjs-org/encapsulated replaces @dcmjs-org/pdfs, @dcmjs-org/imaging holds buildImageDataset and parseJpegInfo, and @dcmjs-org/media and @dcmjs-org/fhir come from 1.0-beta unchanged. Keep only the wrapper on top: the @dcmjs-org/dcmjs rename without "private", the media/encapsulated/image/fhir namespaces in src/index.js, the root dependency on @dcmjs-org/media, test/bundle-size.test.js, and the pnpm 12.9.1 pin. The dcmjs.fhir namespace tests move from packages/fhir/test to test/fhirNamespace.test.js, so the package tests stay off the root wrapper. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
🎉 This PR is included in version 1.0.0-beta.3 🎉 The release is available on:
Your semantic-release bot 📦🚀 |
This is the assembly PR for the pdfs package: it brings
release/1.0-beta-pdfsinto1.0-beta, carrying PR #572 on top of the core engine branch, individually reviewed with its own plain-English description. Like the schemas assembly (#543) it's open as a draft on purpose — please don't merge it yet; the landing order in RELEASE_PLAN.md and the trunk overlap (details below) mean the assemblies should go in deliberately, not as soon as they're green.What this is in plain terms. Hospitals wrap PDF reports — discharge summaries, external referral letters, scanned documents — inside DICOM instances so they can live in the PACS next to the images they describe.
@dcmjs-org/pdfsis both directions of that workflow:encapsulatePdf(pdfBytes, options)turns a PDF into a conformant naturalized Encapsulated PDF dataset (PS3.3 A.45.1, SOP Class 1.2.840.10008.5.1.4.1.1.104.1) ready for the Part 10 writers, minting fresh UIDs by default or attaching into an existing study when you passStudyInstanceUID;extractEncapsulatedPdf(dataset)pulls the exact PDF bytes, MIME type, and document title back out of a parsed instance. The package's entire dependency list is@dcmjs-org/core— no@dcmjs-org/legacyanywhere, including the tests, which round-trip through this branch's own engine (fromDataSet→Part10Writer→fromPart10→NaturalizedListener).A worked example. I ran this on this branch before writing it down; both
console.loglines are the actual output:Review finding 16, fixed inside the port. The v2 extractor trimmed a trailing
0x00from any even-length payload, assuming it was the writer's odd-length OB pad byte — but the writer pads only odd lengths, so a stored even length is ambiguous, and an even-length original genuinely ending in a zero byte came back one byte short. The port fixes this the way the PR #512 review prescribed and the video path already does:encapsulatePdfrecordsEncapsulatedDocumentLength (0042,0015)with the exact original length, andextractEncapsulatedPdfslices to the declared length when present, keeping the trim heuristic only as the fallback for files written without the element. The regression tests were written against the ported-unfixed code and observed failing (the 10-byte zero-tail payload came back as 9 bytes) before the fix turned them green.Two departures from the v2 module, declared. Only the PDF half of
src/encapsulated/comes over — the video half and thetoPdf/fromPdffacade factories insrc/eventStream/api.jsbelong to the media wave. And the v2 suite's last test readtest/sample-dicom.dcm, whose DATACITATION provenance is still being traced; rather than carry that into the new package, the rejection test round-trips a synthetic MR instance through the same pipeline — same proof, no fixture.Breaking changes, honestly. None for readers:
extractEncapsulatedPdfhandles files with and without the length element, so anything the v2 code could extract, this extracts — and even-length payloads ending in a zero byte, which the v2 code silently corrupted, now come back intact. For writers, datasets built byencapsulatePdfnow carry one additional element,EncapsulatedDocumentLength (0042,0015); it's a standard optional attribute of the Encapsulated Document module, so the written output remains conformant — the change is additive.Test evidence. 868 tests across 71 suites — 856 passing, 12 skipped (the pre-existing skips), zero failures — on Node 22 and 24: the full regression bank plus the new 12-test
packages/pdfs/test/encapsulatedPdf.test.js(the eight ported tests and the four finding-16 tests). CI is green at the branch tip7563129: tests, lint/format, and pnpm audit. To run just the package suite:Expected: 1 suite, 12 tests, all passing in under a second.
The trunk overlap. This branch was cut from the tip of
release/1.0-beta-core(e5f46e4), so the diff against1.0-betacurrently shows the whole core engine history plus this one package. That's the same situation #543 described: whichever assembly merges first absorbs the shared trunk, and when the core assembly (#542) goes in, this PR's diff shrinks to justpackages/pdfs/and the lockfile line. Reviewing here means reviewing PR #572; the rest is #542's review.🤖 Generated with Claude Code
Update — the
encapsulatedecorator and hierarchical inheritance (post-review). Following Bill's review, the package grew a generic builder and the inheritable-attribute machinery moved to core.encapsulate(bytes, { baseDicom, mimeType, instance, dataLevel, ...overrides })is the general Encapsulated Document builder;encapsulatePdfis now a thin decorator that checks the PDF magic and supplies the PDF base defaults. The level Sets (patientTags/studyTags/seriesTags) andcopyAttributesByLevellive in@dcmjs-org/corenow, with the same names as the Cornerstone3D adapters so the vocabulary is shared (closes #612).The interesting part is
dataLevel: context inheritance is hierarchical and cumulative. HandencapsulatePdfan instance from the study you're filing under and the Patient + General Study attributes come across, while the document's own identity is always minted fresh — a report can never inherit the source's SOP/Series UIDs or Modality.And the round trip back out is unchanged:
Test evidence (updated). The package suite is now 27 tests (19 PDF + 8 generic/decorator), with 10 more in core for
copyAttributesByLevel; the full suite is 951 passed / 12 skipped / 0 failed. Run just the package:npx jest packages/encapsulated packages/core --testTimeout 60000. Extraction stays PDF-only this PR; a genericextractEncapsulatedis tracked in #614.Update —
createInstancein core, composable base blocks, and the level rule.This update (commit 66af835) replaces the
encapsulatemerge with a genericcreateInstancein@dcmjs-org/core. The update also fixes thedataLevel: "series"behaviour. The level rule below replaces the identity guard of the previous update.§ User requirements
These are the behaviours that a caller can rely on. A change to one of these needs a statement in the PR.
instance, the result is a new object: a new study, a new series, a new SOP instance, the dates of today, and empty Type 2 attributes.instance, the attributes ofdataLeveland of each level above it come frominstance. The levels belowdataLevelare new.patient: the same patient, in a new study.study(the default): the same study, in a new series.series: the same series (its UID, number, and description), as a new SOP instance.instancelevel. The instance attributes do not have a fixed list. The caller sets them as explicit options, for example a specificSOPInstanceUID.mimeType. IfmimeTypeis not set, the MIME type is the explicit or inheritedMIMETypeOfEncapsulatedDocument. If that is not set, the MIME type comes from the base.ModalityorSOPClassUIDis different from the base, the builder logs a warning. The builder keeps the inherited value.extractEncapsulatedPdfreturns the same bytes that the caller encapsulated. This includes an even-length document that ends in a zero byte.predecessor: true, the new document lists eachinstanceinPredecessorDocumentsSequence (0040,A360). The new document replaces the older documents. The builder does not change or delete the older documents. To put the new version in the series of the old version, usedataLevel: "series".Changes to user behaviour in this update:
dataLevel: "series", the result is now in the source series. Before this update, the result was in a new series, but it had the series number and the series description of the source series.instancevalue ofdataLevelis removed, and the builder now throws an error for it. Before this update,instancegave the same result asseries, so the value did not work as its name says.MIMETypeOfEncapsulatedDocumentnow wins over the base value.sourceInstancealias is removed. The package is not published, so no caller uses the alias.predecessoroption lets one document replace another document (ENC-USR-8).§ Implementation requirements
The approach can change when a better approach is available.
createInstance,copyAttributesByLevel,DATA_LEVELS, and the core base blocks are in@dcmjs-org/core. The encapsulated package adds only the document blocks and the payload.baseDicomis a base block. A base block is an object, a function(context) => object, an array of blocks, orcombineBases(...blocks). A later block wins. A combined block keeps its parts in.items.defaultInstanceBase(core):patientBase,studyBase,seriesBase,instanceBase,equipmentBase.encapsulatedBase:defaultInstanceBase,encapsulatedDocumentBase(the SC Equipment conversion attributes and the Encapsulated Document module), andpredecessorBase.encapsulatedPdfBase:defaultInstanceBase,encapsulatedDocumentBase,predecessorBase, andpdfBase(the SOP class, ModalityDOC, andapplication/pdf).dataLevel. The blocks usecontext.inherits(levelName). A function block can calculate a value from other data. For example,nextSeriesNumberBase(qidoSeries, filter)setsSeriesNumberto 1 more than the largest series number in a QIDO-RS series response.{ name, tags }entries, in thelevelsoption.extendDataLevelsadds attributes to a level. A new level is a new entry. The level Sets use the names of the Cornerstone3D adapters. dcmjs also addsPatientAge,PatientSize, andPatientWeightto the study level.instance. To clone them, the caller passesinstance: deepCloneInstance(source), withdeepCloneInstancefrom@dcmjs-org/core.deepCloneInstancedoes not copy binary values (ArrayBuffers and typed arrays) unless the caller gives{ copyBinary: true }, because a copy of large binary data can use all the memory. For a function block,deepCloneInstance(block)returns a function that clones the result of the block on each call. For a promise,deepCloneInstancereturns a new promise for a clone of the value. The builder does not clone, because the usual caller does not change the source after the copy. The builder freezes no object, so a caller can change the result after the call._metais Explicit VR Little Endian, frominstanceBase. A writer that stores a different transfer syntax must update_meta.EncapsulatedDocumentLength (0042,0015)records the exact length, and extraction uses that length. If the element is not present, extraction removes one trailing NUL byte from an even-length payload, because the writer adds that pad byte.predecessorBase(core) reads thepredecessorflag of the context. The block builds the sequence withhierarchicalReferences(instances): one item for each study, then for each series, then for each SOP instance. Only the encapsulated bases includepredecessorBase;defaultInstanceBasedoes not. The Encapsulated Document module does not define the attribute, and does not forbid it. Thus the attribute is a Standard Extended SOP Class attribute.Tests
copyAttributesByLevel.test.js(8 tests) andcreateInstance.test.js(11 tests).encapsulate.test.js(5 tests) covers the base composition, the MIME type precedence, the replacement of a document with a predecessor reference, and a round trip with inherited context.encapsulatedPdf.test.js(11 tests) covers the PDF defaults, the PDF extraction, and finding 16.test/part10Helpers.js.The future fluent API (
encapsulate(bytes).base(...).inherit(...).build()) is now an issue, and is not a code comment: #615.🤖 Generated with Claude Code