Skip to content

feat: @dcmjs-org/schemas — the naturalized-rules catalog - #543

Merged
wayfarer3130 merged 33 commits into
1.0-betafrom
release/1.0-beta-schemas
Oct 17, 2026
Merged

wayfarer3130 merged 33 commits into
1.0-betafrom
release/1.0-beta-schemas

Conversation

@awatson1978

@awatson1978 awatson1978 commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator

This is the assembly PR for the schemas package: it brings release/1.0-beta-schemas into 1.0-beta, carrying PRs #522 and #523 on top of the shared docs-and-fixtures trunk, each individually reviewed with its own plain-English description. It's step 3 of the landing order in RELEASE_PLAN.md section 6, and like the core assembly (#542) it's open as a draft on purpose — please don't merge it yet; the landing order 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. The "naturalized" representation is the plain-JavaScript view of a DICOM dataset — dataset.PatientID instead of raw tag numbers. Until now, the rules governing that view (which keyword each tag maps to, whether a value is a scalar or an array, what a PN or a date is allowed to look like) lived implicitly in parser code. @dcmjs-org/schemas makes them explicit. The per-attribute rules — keyword, VR (the type), VM (how many values), and the naturalized cardinality — cover every standard DICOM attribute, 5,159 of them (the full 5,165-entry packed dictionary minus three structural FFFE items and three retired tags the dictionary carries without a keyword). They are not a committed table: the rules module derives them on demand from the packed dictionary that @dcmjs-org/core already ships, through the same isMultiVM rule the runtime uses, so the schema and the runtime cannot drift apart. The rules are then projected into the two artifacts that must be static files: a JSON Schema (draft 2020-12) for validators like ajv, and generated TypeScript declarations for editors. The catalog also freezes the contract decisions for the naturalized model in an envelope block — VM-based cardinality, values as dcmjs returns them (values: "asReturned"), PersonName as a component object, sequences as a dataset array or the single item, creator-grouped private tags — so later packages can cite one normative source instead of re-deciding.

A worked example. The rules derive lazily and cache; look up any attribute by bare tag:

import { getAttributeRule, envelope, vrFormats } from "./packages/schemas/src/schema/naturalizedRules.js";

getAttributeRule("00100020"); // { keyword: "PatientID", vr: "LO", vm: "1", multi: false }
getAttributeRule("00080008"); // { keyword: "ImageType", vr: "CS", vm: "2-n", multi: true } — always a list
getAttributeRule("00189810").vr; // ["US", "SS"] — a multi-VR code resolved to an explicit union
vrFormats.DA; // { pattern: "^\\d{8}$" } — Part 5 formats, documentation not validation
envelope.values; // "asReturned" — the schema describes what dcmjs returns

And regeneration is one deterministic function — the builder is deliberately pure (no file I/O, no import.meta) so jest can import it, which is exactly how the freshness gate works:

import { buildCatalog, typesSource, jsonSchemaSource } from "./packages/schemas/generate/buildCatalog.mjs";

const catalog = buildCatalog(); // derives the rules; throws loudly on anything unclassifiable
// the CI determinism gate: both projections must equal the committed files
expect(typesSource(catalog)).toBe(read("types/dcmjs-schema.d.ts"));
expect(jsonSchemaSource(catalog)).toBe(read("schema/naturalized.schema.json"));

What's in it. Three groups, in the order they landed:

The shared trunk (the same docs-and-fixtures base that draft #542 carries): RELEASE_PLAN.md, the writing style guide, the PR template, DATACITATION.md, the lockstep prerelease publishing config (.releaserc.json plus the stamp-workspace-versions script and its test), the pipeline smoke test, the Node-24 fixture-reading helper, the @dcmjs-org/fixtures package (the six committed test DICOM files moved by pure git mv, every suite routed through fixturePath()), and the pnpm-overrides fix for the pre-existing audit advisories. Because both assemblies carry this trunk, whichever one merges first absorbs it and the other's diff shrinks to just its own package.

The generator (#522): packages/schemas/generate/ — buildCatalog.mjs (the pure builder), schemaRules.mjs (the rule tables: parseVm() for VM patterns like 1-n and 3-3n, the VR-to-JS-type maps, the Part 5 VR_FORMATS constraints, the excluded structural tags), and generate-schema.mjs (the CLI shell that owns the filesystem writes). Plus the root babel.config.js that lets jest transform files under packages/.

The artifacts and their gates (#523, reshaped by the 2026-10-16 review): the two generated files — schema/naturalized.schema.json and types/dcmjs-schema.d.ts — plus the hand-written rules module src/schema/naturalizedRules.js they derive from, and the hand-written gates in a second commit: the freshness/determinism jest gate shown above, spot-check suites for the catalog and the JSON-Schema projection, a tsc consumer check that compiles realistic usage of the declarations (including @ts-expect-error lines for things that must NOT compile, like treating ImageType as a plain string), and the schema-freshness.yml CI workflow that reruns the generator and fails if the committed artifacts differ.

Test evidence. 347 tests across 28 suites, all passing on Node 22 and 24 — the full pre-existing regression suite plus the five schema suites (test/schema/schemaRules.test.js, test/schema/naturalizedRules.test.js, test/schema/jsonSchemaProjection.test.js, test/schema/naturalizedValidation.test.js, test/schema/catalogConsumer.test.js). CI is green at the branch tip d436fa8: tests, schema artifacts are reproducible, lint/format, and pnpm audit.

The GitHub issues this addresses. I'll be honest about the shape of this list: it's thinner than the core assembly's, because this package is enabling infrastructure — the diff touches nothing under src/, so no runtime bug is fixed here and no issue closes on merge. I've kept it to issues where the connection is real; the broader VR/VM bug backlog belongs to the engine-fix PRs on the core branch, not here.

Contract outcomes frozen into the catalog (the runtime-side tests live on the core branch; the catalog makes each resolution a normative, machine-checkable artifact):

  • #3 (closed) — MappingResource vs MappingResourceUID must naturalize to distinct keywords — the catalog carries 00080105 → MappingResource (CS) and 00080118 → MappingResourceUID (UI) as two entries, no suffix-dropping possible
  • #6 (closed) — the NDD naming contract — keywords keep their UID/Sequence suffixes throughout the catalog
  • #218 (closed) — the single-item sequence shape — the 1.0 VM rule that landed with feat: dcmjs core — the event-stream reading engine and the green regression tests #542 naturalizes a single-item sequence as the item itself (with a hidden [0], a length, and an iterator), and the envelope freezes that as sequences: "datasetArrayOrItem"
  • #381 / #413 (both closed) — PN values as component objects — frozen as personName: "componentObject", so later packages cite one source instead of re-litigating

Open issues whose eventual fix consumes this catalog (the machinery list):

  • #345 (open) — the anonymizer's getTagsNameToEmpty contains names that aren't real dictionary keywords; validating that list against the catalog is exactly the fix
  • #231 (open) — re-naturalizing PN throws Cannot redefine property: Alphabetic; the fix implements the personName: "componentObject" envelope rule
  • #114 (open) — should naturalizing unpack OverlayData/palette bulk; the envelope's bulk: "referenceOrBinary" decision is the answer that fix will implement
  • #388 (open) — denaturalizing sequences with private tags fails; the envelope pins privateTags: "creatorGrouped"
  • #457 (open) — the runtime's VRInstances is missing OL, OV, SV, and UV; the catalog already carries those VRs, making the runtime gap enumerable rather than anecdotal

Test usage and examples. Everything below is copy-paste from the repo root; I ran each one on this branch before writing it down. The reproducibility gate — the same pair of commands schema-freshness.yml runs in CI — regenerates all three artifacts and then requires the working tree to be clean, proving the committed output is byte-identical to what the generator produces:

pnpm run generate-schema && git diff --exit-code packages/schemas

That takes about 1.5 seconds, prints wrote types/dcmjs-schema.d.ts and wrote schema/naturalized.schema.json, and the diff comes back empty. The three schema suites run in isolation with:

npx jest test/schema --testTimeout 60000

Expected: 5 suites, 36 tests, all passing in a few seconds. The tsc consumer check — the same invocation CI uses — compiles realistic usage of the generated declarations under --strict, including the @ts-expect-error lines for shapes that must not compile:

pnpm run check:types

Expected: exits clean in under 2 seconds with no diagnostics. And to poke at the catalog the way a consumer would, this one-liner queries it directly:

node --input-type=module -e '
import { naturalizedRules, getAttributeRule } from "./packages/schemas/src/schema/naturalizedRules.js";
console.log(Object.keys(naturalizedRules.attributes).length); // 5159
console.log(getAttributeRule("00100020")); // { keyword: "PatientID", vr: "LO", vm: "1", multi: false }
console.log(getAttributeRule("00080105")); // { keyword: "MappingResource", vr: "CS", vm: "1", multi: false }
console.log(getAttributeRule("00080118")); // { keyword: "MappingResourceUID", vr: "UI", vm: "1", multi: false }
'

The dictionary hash lives on the generated artifacts (x-dicom-dictionary-hash in the JSON Schema, the header of the .d.ts); if yours reads ee8fe7d302cf7594, you're looking at the same derived rule table CI verified — any dictionary drift changes it and trips the freshness gate.

The numbers, with a caveat. After the 1.0-beta resyncs absorbed the shared trunk, 20 files changed, +63,881 / −25 — but the bulk of those lines are the two generated artifacts (the JSON Schema is about 1.1 MB, the .d.ts about 0.5 MB), which carry the line-budget exemption discussed in #523: declared generated output, reproducible by CI from the committed generator. The 642 KB generated catalog is gone — the rules module is 154 hand-written lines. 32 conventional commits, merged (not squashed) so the release tooling sees each one.

Breaking changes. None to runtime behavior: the root src/ is untouched, and the one change under packages/core/src moves the BINARY_VRS set into a shared utility (same values, re-imported by DicomMetaDictionary) and exports it — zero behavior change. The schemas package itself changed shape twice during review (nullable types, $defs, the derive-on-demand rules module), which is fine pre-publication; it stays private until its package-merge review flips it.

Still to come: the IOD catalog half of the schema work (which modules an object must contain, not just what each attribute looks like) is deferred to land with the validation package that consumes it, per the plan. This PR is complete for what step 3 covers — it's draft only because of the assembly sequencing above.


Follow-up to the 2026-10-07 review. All six inline findings are fixed, one commit per finding so each thread can point at its change:

  1. AT is now a number (6eefd1d) — the readers store Tag.readTag(stream).value, so the runtime side wins; FrameIncrementPointer read from a file validates.
  2. Binary VRs are now frame arrays regardless of VM (80f1242) — the 1.0 VM rule that landed with feat: dcmjs core — the event-stream reading engine and the green regression tests #542 made this normative ("a binary VR keeps the list"), so PixelData types as BinaryValue[] and the consumer check indexes a frame.
  3. Union element types get parentheses (8fcb61b) — SelectorSVValue and SelectorUVValue are (number | string)[].
  4. Fixed VMs now emit maxItems (5d4d2e5) — PixelSpacing: [a, b, c] is rejected; 206 fixed-VM properties carry the bound.
  5. The generator throws on a missing or duplicated keyword (5fd9aa8) — the three RETIRED_undefined tags (00180061, 04000315, 300A0782) are excluded explicitly, and the silent keep-first dedup paths are gone from both projections.
  6. The package declares "type": "module" with an exports map and a files list (408e5d1), so importing it no longer warns.

The contract decisions you asked for. For AT and PixelData, the runtime is the contract and the schema now describes it: AT values are numbers, binary values are frame lists. Both follow from the 1.0 VM rule in #542, which also changed the single-item sequence shape — a one-item sequence naturalizes as the item itself, not an array — so this PR updates the sequence contract to match: the d.ts types SQ as NaturalizedDataset | NaturalizedDataset[], the JSON Schema routes every SQ property through one #/$defs/sequenceValue entry, and the envelope token is now sequences: "datasetArrayOrItem" (5a823e6, f5fc62f). The $defs indirection is load-bearing, not cosmetic: inlining the two-branch shape into every SQ property made ajv's compiled validator blow the call stack on real SR files.

The test you recommended. test/schema/naturalizedValidation.test.js (0eedcad) naturalizes the three committed fixture files and validates each against schema/naturalized.schema.json with ajv. It would have caught the AT and PixelData findings, and it caught the sequence-shape mismatch while I wrote it. The structural contract holds with no exceptions. Three value-space divergences remain, pinned in the test until we decide whether the schema describes what dcmjs emits or what Part 5 permits: a zero-length DA naturalizes as "" (the DA pattern has no empty branch), the sample-op file holds the noncompliant age "24" and the schema passes Part 5 judgement on it, and a zero-length DS inside a list naturalizes as a null element. I'd like your read on those three before unpinning them.


Follow-up to the 2026-10-16 review. The rule you proposed is adopted and recorded: envelope.values: "asReturned" — the schema describes what dcmjs returns, and vrFormats documents the Part 5 formats separately (they moved from validation keywords to the x-dicom-format annotation). With that rule the three pinned divergences unpinned themselves: the fixture validation test now expects zero exceptions for all three files.

Blockers, both fixed in 22b5685:

  1. Empty elements — every property type carries null, list entries can be null, and the tsc gate has an @ts-expect-error proving string | undefined alone no longer compiles for PatientID.
  2. Bulk references — binary properties validate through a shared $defs/binaryValue (frame list | one {BulkDataURI}/{InlineBinary} object | null), and the d.ts says BinaryValue | BinaryValue[] | null. Both of your example inputs are now cases in naturalizedValidation.test.js, plus a null DS list entry.

Should-fixes:

  • The catalog alternative — adopted (dd63127). naturalizedRules.js is now a 154-line hand-written module: the hand-decided data stays (envelope, vrFormats, MULTI_VR, exclusions), and the per-attribute rules derive on demand from the packed dictionary through core's isMultiVM — which also removes the parseVm.multi duplication (parseVm keeps only the VM bounds) and shares BINARY_VRS through a core utility. The JSON Schema and the .d.ts stay generated; the jest determinism gate compares both projections to the committed files.
  • UV/SV — typed as bigint, matching the readers; the README notes that JSON.stringify throws on it. If you'd rather move the readers to the number-or-string rule, that's a core follow-up.
  • Freshness path filter — now watches packages/core/src/dicom.*.js, dictionary.*.js, isMultiVM.js, and binaryVRs.js (806ee8f).
  • Types export — the generated d.ts declares the module exports (naturalizedRules, getAttributeRule, envelope, vrFormats, the AttributeRule interface), and the tsc gate imports them.
  • Exports conditions — a default condition is in.
  • PN constraint — $defs/personName enforces the component object (nullable string components; additional properties stay open for the boxed-String assignment case).
  • DS/IS formats — removed from vrFormats, with a test asserting their absence.
  • Catalog consumer — test/schema/catalogConsumer.test.js walks each fixture's naturalized dataset, looks up every key's rule, and checks list-vs-scalar and the VR's JavaScript type, recursing through sequences.

Nits: the work-breakdown labels and the missing spec citation are gone from the comments; ajv and typescript are exact-pinned; the literal table tests are pruned (parseVm cases stay); and agreed, the MODULE_TYPELESS_PACKAGE_JSON warning for core goes to a core PR, not this one.

Documentation: packages/schemas/README.md now answers the four questions — what the package is for and who uses it, how it differs from the dictionary (rules semantics derived on demand, not a copy), why it lives here, which artifact serves which task — with the ajv usage example you asked for.

🤖 Generated with Claude Code

awatson1978 and others added 6 commits September 28, 2026 23:19
feat: add the @dcmjs/schemas package with the naturalized-rules catalog generator
feat: commit the generated schema catalog with reproducibility gates
@awatson1978
awatson1978 marked this pull request as ready for review September 30, 2026 18:43
@awatson1978 awatson1978 changed the title feat: @dcmjs/schemas assembly — the naturalized-rules catalog, its generator, and reproducibility gates feat: @dcmjs-org/schemas assembly — the naturalized-rules catalog, its generator, and reproducibility gates Oct 2, 2026
awatson1978 and others added 2 commits October 2, 2026 11:09
Drops the scaffold-era private flag and fills in the publish metadata
the other packages already carry: the entry point (the naturalized
rules module), the type declarations, license, and repository
directory. Publishing stays gated behind the publish GitHub
environment — merging this changes nothing on npm.

Co-Authored-By: Claude Fable 5 <[email protected]>
feat: mark @dcmjs-org/schemas publishable
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)
@awatson1978 awatson1978 changed the title feat: @dcmjs-org/schemas assembly — the naturalized-rules catalog, its generator, and reproducibility gates feat: @dcmjs-org/schemas — the naturalized-rules catalog Oct 6, 2026
…schemas

# Conflicts:
#	.github/workflows/publish-package.yml
#	DATACITATION.md
#	RELEASE_PLAN.md
#	pnpm-lock.yaml
#	pnpm-workspace.yaml
#	test/anonymizer.test.js
#	test/async-data.test.js
#	test/data-options.test.js
#	test/data.test.js
#	test/integration/DicomMessage.readFile.test.js
#	test/lossless-read-write.test.js
#	test/normalizers.test.js
#	test/pipeline-smoke.test.js
#	test/testUtils.js
@wayfarer3130
wayfarer3130 marked this pull request as draft October 7, 2026 13:58

@wayfarer3130 wayfarer3130 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of PR #543

This review covers the diff against 1.0-beta. The review does not cover the generated files and the docs line by line. The inline comments give 6 findings.

Merge of 1.0-beta (commit 0940079)

I merged origin/1.0-beta into this branch. The merge had 14 conflicts. Most of the conflicts came from #518 and #519, because those PRs went into 1.0-beta as squash merges.

  • .github/workflows/publish-package.yml: I kept the 1.0-beta version. That version pins the actions by SHA, uses OIDC trusted publishing, and runs pnpm exec semantic-release.
  • RELEASE_PLAN.md: I kept the 1.0-beta version. The copy on this branch had an error from the scope rename: "originally hoped for @dcmjs-org/".
  • The tests, test/testUtils.js, and DATACITATION.md: I kept the version of this branch, because the fixtures moved to packages/fixtures/dicom.
  • pnpm-workspace.yaml: I kept the packages/* entry from this branch and the braces auditConfig from 1.0-beta.
  • pnpm-lock.yaml: I regenerated the lockfile. The result differs from 1.0-beta by about 60 lines (typescript and the packages/schemas importer).

Results after the merge

  • pnpm run check:types passes.
  • pnpm run generate-schema writes no change to packages/schemas.
  • pnpm test: 345 of 348 tests pass. test_multiframe_1, test_oneslice_seg, and test_deflated fail on my Windows machine. These 3 tests use datasets that the tests download, and my local download cache is empty. This PR changes only the fixture paths in test/data.test.js. Thus the cause is probably local. I did not run these tests on 1.0-beta to confirm.

Tests

The schema tests check single attributes, and the freshness test checks that the generator output did not change. No test naturalizes a real file and validates the result against the schema. One such test would find the AT and PixelData findings below. I recommend one test of this type: "the API must do this".

User contract and runtime

The envelope block and dcmjs-schema.d.ts publish a contract for users. For AT and PixelData, this contract differs from the data that dcmjs gives today, and the PR does not say so. A maintainer must decide which side is correct: the schema or the runtime. That decision must go into the PR description.

Draft status

I changed this PR to a draft. The PR description asks that nobody merges the PR yet, and the draft status prevents an accidental merge.

🤖 Generated with Claude Code

throw new Error(`unclassifiable VM pattern: "${vm}"`);
}

const STRING_VRS = "AE AS AT CS DA DT LO LT SH ST TM UC UI UR UT".split(" ");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

AT is in STRING_VRS, but dcmjs naturalizes AT as a number. I wrote FrameIncrementPointer to a file, read the file again, and naturalized the dataset. The value was 1577059, which is a number. Thus a valid dataset fails the JSON Schema, and TypeScript users get the wrong type.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Will move AT to NUMBER_VRS.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 6eefd1d — AT moved to the number VRs, with a comment noting that the readers store Tag.readTag(stream).value. The new naturalize-and-validate test in 0eedcad covers this class of mismatch going forward.


const STRING_VRS = "AE AS AT CS DA DT LO LT SH ST TM UC UI UR UT".split(" ");
const NUMBER_VRS = "DS FL FD IS SL SS UL US".split(" ");
const BINARY_VRS = "OB OD OF OL OV OW UN".split(" ");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

With these rules, the schema types PixelData as one BinaryValue. dcmjs gives an array of frame ArrayBuffer values. I checked this with sample-dicom.dcm. The check in types/checks/consumer.ts thus confirms a type that the real data does not have.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Will update the assertion in types/checks/consumer.ts.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 80f1242 — binary VRs now type as BinaryValue[] regardless of VM, and the JSON Schema makes them arrays with no VM-derived item bounds (the VM does not count frames). The 1.0 VM rule that landed with #542 made this the normative runtime shape. The consumer check now asserts the array and indexes a frame.

if (!multi) {
return scalar;
}
return scalars.length > 1 ? `(${scalar})[]` : `${scalar}[]`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

For UV and SV, scalar is the union number | string in one string, and scalars.length is 1. The result is number | string[], but the correct type is (number | string)[]. The generated d.ts has this error for SelectorSVValue and SelectorUVValue (both VM 1-n). A fix: add the parentheses when scalar contains |.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Will add parentheses

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 8fcb61b with exactly the fix you suggested — the parentheses are added when the scalar contains |, so SelectorSVValue and SelectorUVValue generate as (number | string)[].

if (!isSq && vm.min > 1) {
prop.minItems = vm.min;
}
if (!isSq && vm.max !== null && vm.max !== vm.min) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

For a fixed VM ("2", "3", "6"), vm.max is equal to vm.min, so this condition gives no maxItems. The schema then accepts PixelSpacing: [a, b, c]. 206 properties have this problem. A fix: remove vm.max !== vm.min from the condition.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Will remove vm.max !== vm.min from the condition.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 5d4d2e5 — the vm.max !== vm.min clause is gone, so a fixed VM emits both bounds and PixelSpacing: [a, b, c] is rejected.

const seen = new Set();
for (const [tag, entry] of Object.entries(catalog.attributes)) {
if (seen.has(entry.keyword)) {
continue; // keep first per keyword, matching the d.ts dedup

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The dictionary gives the keyword RETIRED_undefined to three tags that have no relation: 00180061 (DS), 04000315 (FL), and 300A0782 (US). The generator publishes this keyword, and this line keeps only the first tag in the JSON Schema. The generator must stop with an error when a keyword is missing, as it already does for an unknown VR.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Will add those 3 keywordless retired tags to an explicit exclusion and throw on duplicate/placeholder keywords

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 5fd9aa8 — the generator now throws when a keyword is missing (the RETIRED_undefined placeholder) or duplicated, matching the loud failure it already had for an unknown VR. The three keywordless retired tags are excluded through an explicit KEYWORDLESS_TAGS set next to EXCLUDED_TAGS, and the silent keep-first dedup paths are removed from both the d.ts and the JSON Schema projections. A new test asserts keyword uniqueness across the catalog.

"name": "@dcmjs-org/schemas",
"version": "0.0.0",
"description": "Machine-readable catalog of DICOM attributes: names, types, and rules, generated from the data dictionary",
"main": "./src/schema/naturalizedRules.js",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

main points to a file that uses export, but the package has no "type": "module" and no exports field. On Node versions before 22.7, a user of the published package gets a SyntaxError. On newer Node versions, the import gives the MODULE_TYPELESS_PACKAGE_JSON warning. I saw this warning when I imported the file locally. A fix: add "type": "module" and an exports map.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Will add "type": "module" + exports map + files.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in 408e5d1 — the package declares "type": "module" with an exports map (the types entry, the module, and the JSON Schema path) and a files list that ships only the generated artifacts. Importing the module no longer warns.

awatson1978 and others added 10 commits October 14, 2026 11:52
Resolve the conflicts from the core merge (#542):
- DATACITATION.md: take the 1.0-beta table, which has the same
  packages/fixtures paths plus the testImages rows
- babel.config.js: take the 1.0-beta root config with the workspace-wide
  preset; remove packages/schemas/.babelrc, which a root babel.config.js
  no longer honors
- pnpm-lock.yaml: take 1.0-beta and re-resolve with pnpm install

Co-Authored-By: Claude Fable 5 <[email protected]>
The readers store Tag.readTag(stream).value for AT, so a naturalized
AT value is a number, not the "ggggeeee" string of the DICOM JSON
model. FrameIncrementPointer read from a file now validates.

Co-Authored-By: Claude Fable 5 <[email protected]>
A one-string union like "number | string" with VM 1-n produced
"number | string[]". SelectorSVValue and SelectorUVValue are now
"(number | string)[]".

Co-Authored-By: Claude Fable 5 <[email protected]>
A binary Value lists frames, so PixelData and the other binary VRs
naturalize as an array even with VM 1. The consumer check now asserts
BinaryValue[] and indexes a frame.

Co-Authored-By: Claude Fable 5 <[email protected]>
A fixed VM ("2", "3", "6") has vm.max equal to vm.min, and the old
condition skipped maxItems in exactly that case, so the schema accepted
PixelSpacing: [a, b, c]. 206 fixed-VM properties now carry the bound.

Co-Authored-By: Claude Fable 5 <[email protected]>
…d tags

The dictionary gives the placeholder keyword RETIRED_undefined to three
unrelated tags (00180061, 04000315, 300A0782), and the projections kept
only the first. The generator now throws on a missing or duplicated
keyword, the three keywordless retired tags are excluded explicitly, and
the silent dedup paths in the d.ts and JSON Schema projections are gone.

Co-Authored-By: Claude Fable 5 <[email protected]>
The 1.0 VM rule naturalizes a single-item sequence as the item object
itself (with a hidden [0], a length, and an iterator), not an array.
The d.ts now types SQ as NaturalizedDataset | NaturalizedDataset[], the
JSON Schema uses oneOf, and the envelope token is datasetArrayOrItem.

BREAKING CHANGE: envelope.sequences changes from datasetArray to
datasetArrayOrItem, and the generated SQ property types widen.

Co-Authored-By: Claude Fable 5 <[email protected]>
main points at a file that uses export, but the package had no type
field, so Node before 22.7 fails with a SyntaxError and newer Node warns
MODULE_TYPELESS_PACKAGE_JSON. The package now declares type module, an
exports map with the types entry and the JSON Schema path, and a files
list that ships only the generated artifacts.

Co-Authored-By: Claude Fable 5 <[email protected]>
Inlining the two-branch sequence shape into every SQ property made the
compiled ajv validator exceed the call stack, at compile time without
allErrors and at validation time with it. Every SQ property now refs
#/$defs/sequenceValue, which ajv compiles once.

Co-Authored-By: Claude Fable 5 <[email protected]>
…hema

Naturalize the three committed DICOM files and validate the result with
ajv against schema/naturalized.schema.json. The structural contract
holds with no exceptions; the three known value-space divergences
(zero-length DA as "", a noncompliant AS value passed through, a
zero-length DS list element as null) are pinned in the test until the
value-format contract is decided.

Co-Authored-By: Claude Fable 5 <[email protected]>
@awatson1978
awatson1978 marked this pull request as ready for review October 14, 2026 20:19
Take the 1.0-beta lockfile and re-resolve with pnpm install, keeping
the ajv devDependency and the scoped semver@6 override pin.

Co-Authored-By: Claude Fable 5 <[email protected]>

@wayfarer3130 wayfarer3130 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@awatson1978 thank you for the follow-up. The six fixes from the 2026-10-07 review are correct. The new fixture validation test is a good addition, and it already found a real problem.

I checked out 6eb1ed2 and ran the gates. pnpm run generate-schema gives no diff, pnpm run check:types is clean, and the 4 schema suites pass (31 tests).

Documentation request

From the code, I cannot see clearly what the schemas package is for. Please add a short section to packages/schemas/README.md that answers these questions:

  1. What is the purpose of @dcmjs-org/schemas? Who uses it, and for which task?
  2. How does the catalog differ from the tag data that dcmjs already has? The attributes table holds {keyword, vr, vm} for each tag. getAllStandardTagEntries() in packages/core/src/dicom.lookup.js already gives the same data from dicom.packed.js.
  3. Why is the package in this repository, and why does a consumer not generate the artifacts from the dictionary?
  4. Which artifact must a consumer use for which task? For example: the JSON Schema to validate a naturalized dataset, and the .d.ts for editor types. What task needs naturalizedRules.js?

A short usage example in the README also helps. For example, show how to validate a naturalized dataset, the same as test/schema/naturalizedValidation.test.js does.

Blockers

1. Empty elements. naturalizeElement returns null for an element that is present but empty, for example a type 2 attribute. The JSON Schema and the .d.ts do not permit null.

DicomMetaDictionary.naturalizeDataset({ "00100020": { vr: "LO" } });
// → { PatientID: null }
// ajv: "/PatientID must be string"

The .d.ts declares PatientID?: string. Strict TypeScript compiles ds.PatientID.length, and the code then fails at runtime. The fixture test passes only because the three fixture files have no such element.

2. Bulk data references. For binary VRs, the schema requires an array. A binary element with only a BulkDataURI or an InlineBinary naturalizes to one object (packages/core/src/DicomMetaDictionary.js, lines 16-21). DICOMweb JSON gives this shape for most pixel data.

DicomMetaDictionary.naturalizeDataset({
    "7FE00010": { vr: "OB", BulkDataURI: "http://host/bulk/1" }
});
// → { PixelData: { BulkDataURI: "http://host/bulk/1" } }
// ajv: "/PixelData must be array"

The .d.ts type BinaryValue[] lets ds.PixelData?.[0] compile, but the result is undefined at runtime. The envelope says bulk: "referenceOrBinary", but the projections do not use that token. A $defs/binaryValue entry with BinaryValue | BinaryValue[] can fix the problem, the same as sequenceValue.

Please add both inputs to naturalizedValidation.test.js.

Your three pinned divergences. These two blockers and your three divergences have one root question: does the schema describe what dcmjs returns, or what Part 5 permits? I recommend this rule: the schema describes what dcmjs returns, and vrFormats documents the Part 5 formats separately. With that rule, the schema accepts the empty DA "", the age "24", and the null element in the DS list. A separate Part 5 check can report them. Please record the decision in the envelope.

Should fix

  • UV type. The reader returns a bigint (stream.readBigUint64(), packages/core/src/ValueRepresentation.js line 1382). The types say number | string, and the schema item is {}. JSON.stringify(ds) throws on the value. Type UV as bigint, or change the reader to the string rule that the comment describes.

  • Path filter of schema-freshness.yml. The filter watches src/dicom.packed.js and src/dictionary.*.data.js. These files are now one-line re-exports of packages/core/src/. A change to packages/core/src/dicom.packed.js does not start the workflow. The jest determinism test compares only the catalog, so the .d.ts and the JSON Schema can become old without a failure. Please add packages/core/src/dicom.*.js and packages/core/src/dictionary.*.js.

  • types export. dcmjs-schema.d.ts does not declare naturalizedRules. In TypeScript, import { naturalizedRules } from "@dcmjs-org/schemas" gives TS2305.

  • exports conditions. The map has only an import condition, so require() gets ERR_PACKAGE_PATH_NOT_EXPORTED. Please add a default condition. The package is private, so this item can wait for the package-merge review.

  • parseVm().multi copies isMultiVM. packages/core/src/utilities/isMultiVM.js has the same rule, and the two disagree on "0-1". The dictionary has no "0-1" VM today, so nothing fails yet. Please use isMultiVM in the generator, so that the runtime and the schema share one rule. The same applies to BINARY_VRS, which DicomMetaDictionary.js also defines.

  • PN constraint. The schema has no type for PN properties, so any value validates. A $defs/personName object enforces personName: "componentObject".

  • DS and IS in VR_FORMATS. These entries never apply, because DS and IS map to number. Please remove them, or document them as raw-string constraints. Two tests assert these entries, so a reader can think that the schema validates the DS and IS lengths.

  • The catalog repeats the dictionary. naturalizedRules.js is 642 KB (64 KB gzip). No runtime code imports the catalog, so the load time of dcmjs does not change. A direct import costs about 9 ms and 2.8 MB of heap on Node 24. The packed dictionary costs about 2 ms and 1 MB. Which consumer needs the full table as a static module? An alternative is possible:

    • keep envelope, vrFormats, MULTI_VR and the exclusion lists as hand data;
    • derive the attribute rules on demand from the packed dictionary and isMultiVM.

    That alternative also removes the parseVm item. The JSON Schema and the .d.ts stay generated files, because ajv and tsc need static input.

  • No example uses the catalog with a dataset. The tests use naturalizedRules only for single lookups and for the determinism gate. The real-data test uses the JSON Schema, not the catalog. Please add one test that walks a naturalized dataset with the catalog. For each key, the test looks up the rule, and then checks scalar or array and the VR type. Without such a consumer, it is difficult to justify the catalog.

Nits

  • The comments contain work-breakdown labels: D13, D14, D22, D27 decision 3. schemaRules.mjs line 2 cites docs/superpowers/specs/2026-07-03-d22-naturalized-schema-design.md, and that file is not in the repository. Please remove both.
  • ajv and typescript use caret ranges (^8.20.0, ^6.0.3). The other devDependencies have exact pins. A minor release of tsc can change the result of an @ts-expect-error line in consumer.ts.
  • schemaRules.test.js repeats VR_SCALAR, MULTI_VR, VR_FORMATS and EXCLUDED_TAGS literally. Each table change then needs two edits. Keep the parseVm cases, and think about removing the literal table tests.
  • pnpm run generate-schema prints a MODULE_TYPELESS_PACKAGE_JSON warning for packages/core/package.json. The fix belongs in core, not in this PR.

awatson1978 and others added 4 commits October 16, 2026 12:53
The committed 642 KB catalog repeated the packed dictionary that dcmjs
already ships. src/schema/naturalizedRules.js is now a hand-written
module: the hand-decided data stays (envelope, vrFormats, MULTI_VR, the
exclusion lists), and the per-attribute rules derive lazily from
getAllStandardTagEntries through the same isMultiVM rule the runtime
uses, so the two cannot drift. Each rule carries multi, and BINARY_VRS
moves to a shared core utility that DicomMetaDictionary and the schemas
package both import. parseVm loses its competing multi field and keeps
only the VM bounds for the JSON Schema. The generator consumes the src
module and writes only the two artifacts that must be static for ajv
and tsc: the JSON Schema and the .d.ts. The jest determinism gate now
compares those two projections to the committed files.

The envelope gains values: "asReturned" — the schema describes what
dcmjs returns, and vrFormats documents the Part 5 value formats
separately (DS and IS are absent there, because they naturalize as
numbers). The vrFormats stop being applied with the nullability fix,
which lands next.

BREAKING CHANGE: naturalizedRules.attributes is a derived, cached
getter instead of committed data; entries carry a multi flag;
dictionaryHash lives only on the generated artifacts.

Co-Authored-By: Claude Fable 5 <[email protected]>
The schema now describes what naturalizeDataset returns (envelope.values
"asReturned"):

- A present-but-empty element is null, so every property type carries
  null, and list entries can be null (a DS list holds null for an empty
  entry).
- A binary value is a frame list OR one bulk reference object
  ({BulkDataURI} | {InlineBinary}), through a shared $defs/binaryValue.
- A PN value is the component object, enforced through $defs/personName.
- UV and SV are bigint — the readers store readBigUint64/readBigInt64
  values. JSON.stringify throws on them; the type now says so.
- The Part 5 value formats move from validation keywords to the
  x-dicom-format annotation; vrFormats documents them separately.

The fixture validation test now expects zero divergences for all three
files and adds the two shapes from the review: a present-but-empty
PatientID and PixelData as a bulk reference, plus a null DS list entry.

BREAKING CHANGE: generated property types are nullable; binary and PN
properties validate through $defs; the JSON Schema no longer enforces
Part 5 patterns or lengths.

Co-Authored-By: Claude Fable 5 <[email protected]>
- The generated .d.ts declares the module exports (naturalizedRules,
  getAttributeRule, envelope, vrFormats, the rule and format interfaces),
  so a TypeScript import of the package resolves without TS2305, and the
  tsc gate now imports them.
- The exports map gains a default condition for require() users.
- schema-freshness.yml watches the dictionary sources where they live
  now (packages/core/src), plus the isMultiVM and binaryVRs rules the
  derivation depends on.
- A consumer-walk test reads each fixture file and checks every
  naturalized attribute against its derived rule: list vs scalar and the
  VR's JavaScript type, recursing through sequences.

Co-Authored-By: Claude Fable 5 <[email protected]>
The README now answers what the package is for and who uses it, how the
rules differ from the raw dictionary (semantics derived on demand, not a
copy), why the package lives in this repository, which artifact serves
which task, and the as-returned value contract — with an ajv usage
example matching the validation test. ajv and typescript move to exact
pins like the other devDependencies, so a minor tsc release cannot
change an @ts-expect-error outcome.

Co-Authored-By: Claude Fable 5 <[email protected]>
@awatson1978

Copy link
Copy Markdown
Collaborator Author

Thank you for the thorough second pass — everything is addressed, and your "schema describes what dcmjs returns" rule is adopted and recorded as envelope.values: "asReturned". Four commits, in review order:

dd63127 — your catalog alternative, adopted. naturalizedRules.js is now a 154-line hand-written module: the hand-decided data stays (envelope, vrFormats, MULTI_VR, the exclusion lists), and the per-attribute rules derive on demand from the packed dictionary through core's isMultiVM, with the same loud failures the generator had. That also resolves the parseVm().multi duplication (parseVm keeps only the VM bounds; "0-1" now follows the one rule) and BINARY_VRS moved to a shared core utility that DicomMetaDictionary and this package both import. The JSON Schema and the .d.ts stay generated; the jest determinism gate compares both projections to the committed files.

22b5685 — both blockers. Every property type carries null (present-but-empty), list entries can be null, binary properties validate through $defs/binaryValue (frame list | one {BulkDataURI}/{InlineBinary} object | null) with the d.ts saying BinaryValue | BinaryValue[] | null, PN goes through $defs/personName, and UV/SV are bigint per the readers (the README notes the JSON.stringify caveat — if you'd rather move the readers to the number-or-string rule, I'd put that in a core follow-up). The Part 5 formats moved from validation keywords to the x-dicom-format annotation, so your three-divergence question is closed: the fixture test now expects zero exceptions for all three files, and both of your blocker inputs are test cases, plus a null DS list entry.

806ee8f — the consumer-facing gaps. The generated d.ts declares the module exports (no more TS2305, and the tsc gate imports them), the exports map has a default condition, schema-freshness.yml watches packages/core/src/dicom.*.js / dictionary.*.js / isMultiVM.js / binaryVRs.js, and test/schema/catalogConsumer.test.js is the consumer you asked for: it walks each fixture's naturalized dataset, looks up every key's rule, and checks list-vs-scalar and the VR's JavaScript type, recursing through sequences.

558f3c8 — docs and nits. The README answers your four questions (purpose and consumers; how the rules differ from the raw dictionary — semantics derived on demand, not a copy; why the package lives in this repo; which artifact for which task) with the ajv example. The work-breakdown labels and the dead spec citation are gone, ajv and typescript are exact-pinned, and the literal table tests are pruned (the parseVm cases stay). Agreed on the MODULE_TYPELESS_PACKAGE_JSON warning — that fix goes to core, not here.

One side note: I hit your test_multiframe_1 / test_oneslice_seg / test_deflated failures locally too. It was a corrupt download cache (a partial extraction left deflate_tests/deflate_tests nested, so SOPClassUID came back undefined from a bad read) — deleting the dcmjs-test temp directory and re-downloading fixed all three. Your empty-cache theory was right, and the cache can also go bad, not just cold.

Verified at the new tip: full suite 897 passed / 0 failed on Node, pnpm run generate-schema leaves a clean tree, pnpm run check:types is clean.

🤖 Generated with Claude Code

@awatson1978
awatson1978 dismissed wayfarer3130’s stale review October 16, 2026 21:08

Change requests applied.

@wayfarer3130
wayfarer3130 merged commit 27d9e4f into 1.0-beta Oct 17, 2026
10 checks passed
@wayfarer3130
wayfarer3130 deleted the release/1.0-beta-schemas branch October 17, 2026 01:28
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 1.0.0-beta.1 🎉

The release is available on:

Your semantic-release bot 📦🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants