Architecture
This document describes the current architecture of json-tology: the contract it upholds, the canonical graph execution model, the public API surface, and the file inventory for every source module.
Contract
json-tology has one authored source and three first-class consumers:
- TypeScript compile-time inference from
as constJSON Schema. - Runtime validation and materialization over the canonical graph.
- JSON-LD serialization of both schema structure (TBox) and validated instances (ABox).
JSON Schema is the authored form. The canonical graph is the runtime artifact. JSON-LD output is projected from that graph. The implementation must not drift into separate semantic engines for typing, validation, ontology, or instance projection.
Non-Negotiable Invariants
These rules govern every remaining workstream:
- JSON Schema remains the authored source language.
@types/json-schemaremains the intentional standards dependency for authoring types.- The graph remains the shared runtime artifact.
- Validation semantics come from graph semantics, not serializer-specific logic.
- RDF semantics are emitted as JSON-LD only in-core.
materialize(),instantiate(),create(), andtoQuads()remain views over one runtime execution model.- Schema round-trip must stay lossless for the supported keyword surface.
- Type inference must either model behavior correctly or fall back explicitly. Silent misresolution is not acceptable.
- Versioning happens in git and releases, not in production runtime code.
- Do not preserve backward compatibility via dual implementations, legacy loaders, or version branches inside active codepaths.
- Completion claims must reflect the code that exists now, not the intended direction.
- Vocabulary plugins extend ontology output without modifying core projection logic. Plugin prefixes merge into the active
Curieinstance; plugin relations are extracted after core extraction; plugin projection runs for non-core predicates. - The canonical bookstore at
examples/docs/bookstore/is the single source of truth for every docs page, every example file, and every benchmark scenario. Docs prose, runnable examples, and bench fixtures all draw from the same registered schemas andaboxFixtures. New example files importbookstoreEntitiesfrom the canonical registry; new docs pages include their code via VitePress<<<directives against a runnable file inexamples/docs/. Standalone synthetic schemas, mini-registries, andJsonTology.create({...})calls inside example files are forbidden — if a surface needs structure the canonical domain doesn't provide, the canonical domain expands to accommodate it. When an example legitimately needs a registry with a non-default option set (e.g.enableTypeCast: true), it seeds the new registry frombookstoreSchemasso every transitive$refresolves. The ratchet atscripts/check-docs-includes.mjsenforces this with a ceiling of zero inline\``tsblocks indocs/**/*.mdoutside two explicit exemption categories: comparator::: code-groupsections (peer-library comparisons), and blocks preceded by(the marker rationale documents why the block cannot be a runnable file — removed/legacy API migration context,.d.tsmodule augmentation, type-shape pseudocode, function-signature pseudocode). There are no file-pattern exemptions; migration pages carry theinline-ts-ok` marker on every block that references a removed API. The canonical narrative is Bastian Balthazar Bux (the customer from the framing story of Michael Ende's The Neverending Story) ordering a rare 1979 first edition of Die unendliche Geschichte (Thienemann Verlag, ISBN-13 9783522128001); all fixture names are either real authors or characters from the book with realistic names. Pronouns referring to fixture personas are gender-neutral throughout. QuadInterfaceis a re-export of@rdfjs/types#Quad(the rdf/js data-model spec). Quads carry the spec-requiredtermType: 'Quad',value: '', andequals(other).subjectis aNamedNode | BlankNode;predicateis aNamedNode;objectis aNamedNode | BlankNode | Literal;graphis aNamedNode | BlankNode | DefaultGraph(non-optional, defaults to the singletonDefaultGraphterm).Literal.valueisstringper the rdf/js spec; the JS type tag is carried inLiteral.datatype.value(xsd:integer,xsd:boolean,xsd:dateTime, etc.). UseTerms.iri(...)/Terms.blank(...)/Terms.literal(...)/Terms.defaultGraph()/Terms.quad(s, p, o, g?)to construct terms and quads; usedecodeLiteral(literal)to recover the typed JS value from a literal. RDF lists are emitted as the standardrdf:first/rdf:rest/rdf:niltriple chain;Lists.build(items)constructs the chain andLists.collect(head, allQuads)walks it back. There is no project-internal list-term abstraction. External quads produced byn3,@rdfjs/data-model,@graphy/core.data.factory, or any other rdf/js-aware library are accepted as-is byfromQuadsandOntologyBuilder.addQuads;Lists.narrowExternalQuads(quads)drops quads containingVariableor quoted-triple terms that this project does not support.- Schema registration is strict-by-default.
enableStrictGraph,enableInlineWarnings, andenableDuplicateDetectiondefault totrue. Registering an inline primitive constraint or a structural duplicate raisesSchemaErrorat registration time. PassenableStrictGraph: falsetoJsonTology.create({...})ornew SchemaRegistry({...})to restore permissive behaviour. fromTbox/OwlImporteris the inverse oftoTbox. It reads an OWL 2 TBox and reconstructs JSON Schema objects for every declared class. There is one import pipeline (OwlImporterwith axiom dispatchers insrc/modules/ontology/importDispatch/); a second semantic model for OWL import is not acceptable. The round-trip contract isfromTbox ∘ toTbox ≈ identityon the supported OWL 2 axiom set.- Codegen (
json-tology/owl-gen) is a one-way build-step tool. It converts an OWL TBox intoas constTypeScript schema literals viagenerateFromTbox(single-file) andgenerateRegistryDirectory(bookstore-layout directory). The generator is pure over theOwlImporterresult; the generated source files are committed to the repo and not re-generated duringnpm testornpm run build.
Verified Current State
The canonical graph is the single runtime artifact. Validation, materialization, ABox projection, OWL/SHACL serialization, and codegen all read from it. The implementation upholds these invariants:
- One canonical artifact shape; one load path. Legacy artifact shapes fail loudly with regeneration guidance.
- The publish surface is controlled. Builds clean
dist,package.jsonuses an explicitfilesallowlist, and a committed pack-surface regression script validates the tarball. - Schema registration is atomic. Failed registration is a no-op; failed overwrite attempts preserve the prior valid entry and caches.
- Transform contracts are directional.
parse()decodes;materialize()andencode()produce typed wire-form output. - Public docs and exported surfaces are aligned. README examples use supported APIs and public API smoke coverage exists in
test/types. - The shipped CLI is the CLI that is tested. Integration coverage runs the built
dist/cli.jsand locks the supported schema-path behavior. - Logger and loader posture is intentional.
Loadersis a lightweight filesystem loader, not a standards validator. - Compile-time inference covers external
$refresolution via explicit references maps;if/then/elseuses a documented sound branch-union approximation. - SHACL JSON-LD emits
jt:*annotations for graph semantics SHACL Core cannot express directly:multipleOf,minItems,maxItems,uniqueItems. - Round-trip artifact coverage includes anchors, dynamic anchors,
contains,patternProperties, and conditionals. - Benchmark reproducibility is verified.
npm run benchcompletes cleanly; the single compiled validation path is exercised by a smoke test.
Mandatory verification commands:
npm run build
npm run type-check
npm run test
npm run type-check:tests:all
npm run pack:check
npm run bench # for any work touching benchmarked paths or performance claimsCompatibility Policy
This repository does not preserve backwards compatibility inside the codebase through versioned interfaces, fallback loaders, or dual implementations.
When a representation changes:
- keep one current implementation in code
- reject old representations loudly
- document the break
- rely on git history and release versioning for historical access
TDD Discipline
All changes follow strict TDD:
- Write or update the failing test first.
- Run the focused test and confirm the failure is the intended one.
- Implement the smallest change that makes the test pass.
- Rerun the focused suite.
- Run the full verification set.
- Update docs only after code and tests match the new claim.
A change is complete only when:
- the code change exists
- the focused regression tests exist
- all verification commands pass
- the docs describe the implemented state accurately
Public API Surface
Nine package entry points control what consumers import. Internal imports reference defining files directly, not entry-point barrels. See Package exports for full per-subpath usage examples.
| Entry point | Exports |
|---|---|
json-tology | Error classes, error-code constants, JsonTology, Compose, GraphEngine, Materializer, GraphOntologySerializer, OntologyBuilder, Curie, Lift, Lists, Projection, Skolemize, Terms, Transform, Changeset, Operations, Path, Resolver, Value, Hash, Loaders, OwlImportError, OWL_IMPORT_ERROR_CODE |
json-tology/value | Changeset, Operations, Value, Hash |
json-tology/schema | Compose, FormatRegistry, SchemaRegistry, Transform |
json-tology/ontology | GraphOntologySerializer, GraphSchemaSerializer, GraphShaclSerializer, OntologyBuilder |
json-tology/owl-gen | generateFromTbox, generateRegistryDirectory, GenerateFromTboxOptions, GenerateRegistryDirectoryOptions, GenerateRegistryDirectoryEntityFile — browser-safe; returns generated TypeScript source as strings with no file I/O |
json-tology/owl-gen-node | writeFromTbox, writeRegistryDirectory — Node.js only; file-writing skin over owl-gen that imports node:fs/node:path and writes generated source to disk |
json-tology/viz | HtmlRenderer, TypeStringEmitter, VizDataCollector |
json-tology/types | All type aliases (FooType) — compile-time only |
json-tology/interfaces | All interface contracts (FooInterface) — compile-time only |
File Inventory
All source files under src/. Organized by directory.
Entry points (src/)
cli.ts— CLI entry; delegates tosrc/modules/cli/CliWriter.tsindex.ts— main package entry (json-tology)JsonTology.ts— top-level facade class; all public methods delegate to modulesontology/index.ts—json-tology/ontologyentryowl-gen/index.ts—json-tology/owl-genentry;generateFromTboxandgenerateRegistryDirectory; browser-safe (nonode:imports; returns source strings)owl-gen-node/index.ts—json-tology/owl-gen-nodeentry;writeFromTboxandwriteRegistryDirectory; Node.js only (filesystem writes vianode:fs)schema/index.ts—json-tology/schemaentryvalue/index.ts—json-tology/valueentryviz/index.ts—json-tology/vizentry
Constants (src/constants/)
Shared constant objects. All module-scoped constants belong here; modules import from this directory.
BASE_SCHEMAS.ts— meta-schema base schema literalsCOMPOSITION.ts— composition keyword sets and class-axiom skip keysDIALECT.ts— dialect configuration and keyword setsEMPTY_SEMANTICS.ts— empty value handling sentinelsERROR_CODES.ts— machine-readable error code enums for all error classesEXECUTION_OPTIONS.ts— default execution option sentinelsFORMAT_PATTERNS.ts— format pattern definitionsFORMAT_REGEXES.ts— compiled regex objects for format validationFORMAT_VALIDATION.ts— format validator function mapGRAPH_REGEXES.ts— compiled regex objects for graph-level parsingIRI.ts— IRI-related constantsJSONLD.ts— JSON-LD keyword constantsLOGGER.ts— logger configuration defaultsNUMERIC.ts— numeric constraint constantsONTOLOGY_PREDICATES.ts— OWL/RDF predicate strings, cardinality kinds, projection handler mapsPAGINATION.ts— pagination defaultsPATH.ts— path-related constantsRESTRICTION.ts— restriction descriptor constantsSCHEMA_KEYWORDS.ts— JSON Schema keyword strings and primitive type listsSCHEMAS.ts— built-in schema constantsSHACL.ts— SHACL predicate and node kind constantsSTANDARD_PREFIXES.ts— canonical prefix-to-namespace map for well-known RDF vocabularies (19 prefixes:jt,owl,rdf,rdfs,xsd,schema,shacl, etc.)STRUCTURAL_HASH.ts— hash algorithm constants for structural schema hashingUUID.ts— UUID generation constantsVISUALIZATION.ts— visualization layout and style constantsXSD_FACETS.ts— XML Schema facet definitionsXSD_MAPS.ts— XSD type-to-string maps and coercion tablesXSD_REVERSE_MAPS.ts— JS-to-XSD type reverse mappings
Errors (src/errors/)
All error classes extend BaseError. Internal imports reference each file directly.
BaseError.ts— base class withcode,retryable,cause,toJson(),flatten()CoercionError.ts— coercion failures; carriesValidationErrorscollection; code:COERCION_FAILEDDecodeError.ts— failure inside adecodetransform function; extendsTransformError; code:TRANSFORM_DECODE_FAILEDEncodeError.ts— failure inside anencodetransform function; extendsTransformError; code:TRANSFORM_ENCODE_FAILEDGraphError.ts— pointer resolution, anchor lookup, ref resolution, dialect issues; codes: seeGRAPH_ERROR_CODEinsrc/constants/ERROR_CODES.tsInstantiationError.ts— schema instantiation failures; codes:INSTANTIATION_FAILED,EXTRA_FORBIDDEN- (no LoadError class) — loader failures use
SchemaLoadErrorTypeinsrc/types/Loader.ts(a discriminated union type, not an error class) MaterializationError.ts— materialization and ABox projection failures; codes:MATERIALIZATION_FAILED,CYCLIC_DATA,INVALID_IRI_VALUE,NON_FINITE_NUMBER,MISSING_GRAPH_IRIOwlImportError.ts— OWL import fatal conditions; carriesaxiomIriandsubjectIri; code:OWL_IMPORT_NOT_IMPLEMENTEDSchemaError.ts— registration, missing$id, structure validation; codes: seeSCHEMA_ERROR_CODEinsrc/constants/ERROR_CODES.ts; includesSCHEMA_ERROR_CODE.DUPLICATE_ID(SCHEMA_DUPLICATE_ID) andSCHEMA_ERROR_CODE.DUPLICATE_SHAPE(SCHEMA_DUPLICATE_SHAPE) used bySchemaRegistryfor duplicate detectionTransformError.ts— base class for directional transform failures; addsdirection,schemaId?,path?; not thrown directly by the libraryValidationErrors.ts— collection class for accumulated validation errors
Interfaces (src/interfaces/)
All interface declarations (FooInterface). Exported via json-tology/interfaces. Each file is a single interface.
ArrayResult.ts— array validation result shapeBuildOptions.ts— graph build option contractChangeset.ts— changeset interfaceCliWriter.ts— CLI output writer interfaceCompiledNodeValidationPlan.ts— compiled per-node validation planCompiler.ts— schema compiler interfaceCompose.ts— composition operation interfacesCompositionAccumulator.ts— composition result accumulatorConfig.ts— registry configuration interfaceCurie.ts— CURIE prefix manager interfaceCustomKeywordEntry.ts— custom keyword registration shapeDefaultResolutionContext.ts— default resolution context interfaceDump.ts— dump/serialize option interfacesDynamicScopeEntry.ts— dynamic scope stack entryError.ts— base error interfaceFormatRegistry.ts— format registry interfaceGraphAccessor.ts— read-only graph accessor interfaceGraphArtifact.ts— compiled graph artifact interfaceGraphEngine.ts— public graph engine interface (GraphEngineInterface)GraphEngineImpl.ts— internal graph engine implementation detailindex.ts— barrel that re-exports all interface contractsInternalExecutionResult.ts— internal per-node execution resultInvariant.ts— schema invariant interfaceJsonSchemaObject.ts— typed JSON Schema object interfaceLogger.ts— logger interfaceMaterializer.ts— public materializer interface (MaterializerInterface)MaterializerImpl.ts— internal materializer implementation detailObjectResult.ts— object validation result shapeOntology.ts— ontology builder interfaceOwlImport.ts—OwlImportResultinterface — shape returned byfromTbox; fields:schemas,invariants,characteristics,sameAs,individuals,unsupportedPrefetch.ts— prefetch loader interfaceProjection.ts— RDF projection interfacePropCheck.ts— property check contextQuad.ts—QuadInterface— re-export of@rdfjs/types#QuadRefDecoder.ts— ref decoder interfaceRefResolutionLoader.ts— ref resolution loader interfaceRefs.ts— ref visit context interfaceRefTarget.ts— resolved ref target interfaceRegistry.ts— schema registry interface (SchemaRegistryInterface)RelationIndex.ts— graph relation index interfaceResolvedRef.ts— resolved$refresultResult.ts— generic result interfaceRootDialectPlan.ts— root dialect plan interfaceScalarResult.ts— scalar validation result shapeSchemaCompilerCheckExecutionContext.ts— check execution context for schema compilerSchemaCompilerGraphContext.ts— graph context for schema compilerSchemaCompilerImpl.ts— internal schema compiler implementation interfaceSchemaCompilerValidatePlanContext.ts— validate-plan context for schema compilerSchemaEntryStore.ts— schema entry store interfaceSchemaGraph.ts— public schema graph interface (SchemaGraphInterface)SchemaGraphImpl.ts— internal schema graph implementation interfaceSchemaIri.ts— schema IRI interfaceSchemaRefWalker.ts— ref walker interfaceSchemaRegistry.ts— schema registry public interfaceSchemaRegistryEntry.ts— single registry entry shapeSerializer.ts— serializer interfaceSimplePredicateEntry.ts— simple RDF predicate entrySnapshot.ts— registry snapshot interfaceTransformBrand.ts— transform brand interfaceTransformFns.ts— transform function map interfaceTransformStage.ts— transform stage interfaceUnevaluated.ts— unevaluated properties/items visit contextValueImpl.ts— internal value implementation interfaceVisitComposition.ts— composition visitor interfaceVisitContext.ts— graph visit context interfaceViz.ts— visualization interfaceVizOptions.ts— visualization option interfaceVocabularyPlugin.ts— vocabulary plugin interface
Type-organization convention
src/types/ and src/interfaces/ have a strict division of purpose enforced by a custom ESLint rule:
src/types/— data substrate. ContainsFooTypetype aliases: raw shapes, unions, branded primitives, option bags, and compile-time utilities. Types describe what data looks like.src/interfaces/— behavioral contracts. ContainsFooInterfacedeclarations: contracts that classes implement (method signatures, property contracts). Interfaces describe what objects can do.
The rule interface-must-be-contract rejects any interface that could be a type alias, and a companion location rule rejects interface declarations outside src/interfaces/. This is mechanically enforced on every commit — no exceptions.
Usage pattern:
- Use
FooInterfacefor type annotations: parameter types, field types, return types. - Use the class directly only for
new Foo()or static method calls. - Classes carry
implements FooInterfaceclauses. - Static-method-only classes (
Compose,Transform,Hash) and the top-level facade (JsonTology) do not require separate interfaces.
Types (src/types/)
All type aliases (FooType). Exported via json-tology/types. Compile-time only.
AboxOptions.ts— ABox projection option typesBaseTypes.ts— primitive base type aliasesBrand.ts— branded type utilitiesCompose.ts— composition type aliasesComputed.ts— computed property type aliasesConstraintBrands.ts— constraint-branded type aliasesDiff.ts— diff type aliasesEffectiveOptions.ts— effective option type aliasesErrorCodes.ts— error code type aliasesFormat.ts— format type aliasesGraphLookup.ts— graph lookup type aliasesindex.ts— barrel that re-exports all type aliasesInfer.ts—InferType<T>and related inference typesInvariant.ts— invariant type aliasesJsonSchema.ts— JSON Schema type aliasesJsonSchemaTypeName.ts— JSON Schema type name unionJtConfig.ts—JsonTologyconfiguration typeLoader.ts— loader option typesLookupSchema.ts— schema lookup type aliasesNormalizedToQuadsOptions.ts— normalized-to-quads option typesQuad.ts— quad type aliasesRawRestrictionDescriptor.ts— raw restriction descriptor typeRegistry.ts— registry type aliasesRestriction.ts— restriction type aliasesRestrictionInfer.ts— restriction inference typesSchema.ts— schema type aliasesSchemaGraph.ts— schema graph type aliasesSchemaLookup.ts— schema lookup type aliasesSchemaRef.ts—$reftype aliasesSchemaRegistryForEachCallback.ts—forEachcallback typeSchemaValidation.ts— schema validation type aliasesSkolemize.ts— skolemization type aliasesSpecialHandlerFn.ts— special handler function typeSubjectGroup.ts— RDF subject group type aliasesTransform.ts— transform type aliasesTypeConfig.ts— type configuration aliasesTypeErrors.ts— compile-time type error typesValidation.ts— validation type aliasesVisitFn.ts— visitor function types
Module: cli (src/modules/cli/)
CliWriter.ts— CLI output formatter
Module: composition (src/modules/composition/)
Compose.ts—allOf,anyOf,oneOf,not,if/then/else,extendcomposition operations
Module: data (src/modules/data/)
Shared data utilities. DataTypes.ts is the canonical location for type guards and shared helpers.
BaseTypes.ts— base primitive type definitionsChangeset.ts— changeset construction and applicationDataTypes.ts— type guards (isRecord,isPlainObject),deepEqualDumper.ts— JSON dump and object serializationFrozen.ts— frozen-object utilitiesOperations.ts— value operation helpersPath.ts— JSON Pointer path utilitiesResolver.ts— value resolverResult.ts— result re-export shim (delegates tosrc/interfaces/Result.ts)StructuralHash.ts— structural schema hashingValue.ts—Valueclass
Module: format (src/modules/format/)
FormatRegistry.ts— format validator registry; consumers register custom format validators
Module: graph (src/modules/graph/)
Canonical graph construction and engine execution. SchemaGraph.ts is the canonical semantic graph. GraphEngine.ts consumes graph node kinds and relations directly.
AboxGraph.ts— lazy, typed in-memory ABox instance graph over projected ABox quads unioned with the registry's TBox quads; exposesresource/instancesentry points returning a fluentCursor; reads associations (object-property edges, inverse-functional identities) directly from the TBoxCursor.ts— lazy, immutable selection of resource IRIs over anAboxGraph; navigation and refinement return a new cursor, terminals materialize the selection into typed instancesEffectiveProperties.ts— the single effective-property walk shared by materialization, RDF lift, and ABox projection; collects ownproperties,allOfmembers, andif/then/elsebranches (first-declaration-wins, cycle-safe, cross-graph$refresolution)GraphArtifact.ts— compiled graph artifactGraphEngine.ts— builds and cachesSchemaGraphinstances; exposessemantics()and the lookup functions consumed bySchemaRegistryandSchemaCompiler; validation runs throughregistry.validator(id).validate()GraphEngineDefaults.ts— default engine option resolutionGraphEngineScalars.ts— scalar validation pathsGraphEngineSupport.ts— engine utility functionsPredicateResolver.ts— resolves and validates property predicate IRIs; rejects multi-fragment IRIs and control characters withGraphErrorcodeINVALID_PREDICATE_IRIRefResolution.ts— canonical single-source$ref→{ graph, node }resolver; all resolution paths (validation, projection, materialization) delegate hereQuadBackedSchemaGraph.ts—SchemaGraphInterfaceimplementation backed by OWL 2 quads; the structural inverse ofOwlProjection.graph(), ingesting projected quads and reconstructing nodes and relations for the import dispatchers to traverseRefDecoder.ts—$refdecode and registry lookupSchemaCursor.ts— lazy, immutable selection of class IRIs in the TBox; navigation (subClassOf) and terminals lift each class IRI to its authored JSON Schema objectSchemaGraph.ts— canonical schema graph; builds and holds node and relation dataSchemaGraphRelations.ts— relation construction helpersSchemaGraphSupport.ts— graph support utilities; primitive constraint and type keyword setsSchemaIri.ts— IRI construction for graph nodes; providesSchemaIri.propertyIri(classId, propertyName)for graph-identity helpers;parseRefandsplitSubjectfor ref/IRI decomposition
Module: hash (src/modules/hash/)
Hash.ts—Hashclass; structural and identity hashing
Module: loaders (src/modules/loaders/)
Loaders.ts— filesystem and fetch schema loaders
Module: materialization (src/modules/materialization/)
Materialization and ABox projection. Materializer.ts projects normalized graph execution into JS values and ABox nodes.
Materializer.ts—Materializerclass; projects graph execution results into typed instances
Module: codegen (src/modules/codegen/)
OWL TBox → TypeScript source code generation. Pure functions with no filesystem side-effects; used by both the owl-gen CLI and the generateFromTbox / generateRegistryDirectory programmatic API.
OwlCodegen.ts—generateTypeScript(result, options)— topological dep-sort, IRI → PascalCase name derivation, collision detection with_2suffix, sameAs /addCharacteristicemission
Module: ontology (src/modules/ontology/)
Serialization over the canonical graph. Ontology output is a serialization of the canonical graph, not a separate semantic derivation.
BaseGraphSerializer.ts— shared serializer baseGraphOntologySerializer.ts— OWL JSON-LD serializerGraphSchemaSerializer.ts— JSON Schema serializer from graphGraphShaclSerializer.ts— SHACL JSON-LD serializerOntologyBuilder.ts— high-level ontology construction facadeOwlImporter.ts— OWL 2 TBox import pipeline; constructs once, accepts multipleimport()/importAsync()calls; stateless across calls
Module: ontology/importDispatch (src/modules/ontology/importDispatch/)
Axiom dispatchers for OwlImporter. Each dispatcher handles a subset of OWL 2 axioms and produces JSON Schema objects, invariants, characteristics, sameAs pairs, or individuals.
Annotations.ts—owl:sameAs,rdfs:subPropertyOfCharacteristics.ts—owl:FunctionalProperty,owl:InverseFunctionalProperty,owl:TransitiveProperty,owl:SymmetricProperty,owl:AsymmetricProperty,owl:ReflexiveProperty,owl:IrreflexivePropertyClassAxioms.ts—owl:Class,rdfs:subClassOf,owl:equivalentClass,owl:disjointWith,owl:complementOf,owl:disjointUnionOfClassExpressions.ts—owl:intersectionOf,owl:unionOf, anonymous class expression nodesDatatypes.ts—owl:oneOfenumerations →enum; XSD datatype range mapping;rdfs:Datatypewithowl:withRestrictionsfacetsIndividuals.ts—owl:NamedIndividual,rdf:typeassertions, data/object property assertionsProperties.ts—owl:ObjectProperty,owl:DatatypePropertywithrdfs:domain/rdfs:range→ JSON SchemapropertiesentriesPropertyRestrictions.ts—owl:Restrictionwithowl:someValuesFrom,owl:allValuesFrom,owl:minCardinality,owl:maxCardinality
Module: quads (src/modules/quads/)
rdf/js quad and term primitives. This is a low layer (above data/, below graph/): graph/, registry/, materialization/, and rdf/ all import these primitives; the primitives import only data/, constants/, types/, interfaces/, and errors/. They never import rdf/ (projection) or any higher module — this is the boundary that keeps the onion intact and is what the XSD_MAPS/XsdTypes circular violated before extraction.
Curie.ts— CURIE prefix managerIdentifierIssuer.ts— per-call blank-node counter; each projector call constructs its own issuer so concurrent serializations never share mutable counter stateLists.ts— RDF list construction (Lists.build), walking (Lists.collect),Quad_Objectnarrowing (Lists.asQuadObject), and external-quad narrowing (Lists.narrowExternalQuads). All access is through theListsnamespace object.QuadFactory.ts— quad/term construction with CURIE expansion and predicate-IRI validation. The boundary rule:Terms.*is the plain rdf/js term factory (no validation);QuadFactory.*is the graph-serialization-aware layer (CURIE expansion + predicate validation). UseTermsfor raw term construction,QuadFactoryfor projection output.Terms.ts— rdf/js-spec term factory; producesNamedNode/BlankNode/Literal/DefaultGraph/Quadwithout requiring@rdfjs/data-modelat runtime; exportsdecodeLiteral(literal)for typed-JS recoveryXsdTypes.ts— XSD type resolution helpers (consume the pure-data maps insrc/constants/XSD_MAPS.ts)
Module: rdf (src/modules/rdf/)
RDF/JSON-LD output (projection layer). Projections read graph.allRelations() and emit vocabulary-specific quads, building terms via quads/QuadFactory.
JsonLdFormatter.ts— converts quads to JSON-LD nodes; detects rdf:first/rdf:rest list heads and emits@listJsonLdToQuads.ts— inverse ofJsonLdFormatter; converts compact JSON-LD back toQuadInterface[]Lift.ts— lifts external rdf/js quads into typed JS objects; decodes literals viaTerms.decodeLiteralOwlProjection.ts— OWL-specific quad projectionProjection.ts— shared RDF projection base; predicate and handler mapsProjectionHelpers.ts— shared helpers forOwlProjectionandShaclProjection:propertySubjectIri,resolvePropertySchema,resolveRestrictionOnProperty,findAnnotatedEdgeStructureProjectionIndex.ts— relation-to-predicate indexQuadEmit.ts— relation-index → literal-quad emit helpers (emitLiterals,emitConstraintLiteral) used by the OWL/SHACL projectors; delegates term construction toquads/QuadFactoryShaclProjection.ts— SHACL-specific quad projectionSkolemize.ts— blank-node skolemizationVocabProjection.ts— vocabulary plugin projection
Module: registry (src/modules/registry/)
Schema registration and loading. Registration is atomic; failed registration is a no-op.
ComputedStore.ts— computed schema storeInvariantStore.ts— invariant storage and lookupRefResolutionLoader.ts— resolves$reftargets across registry entriesSameAsStore.ts—owl:sameAsequivalence storeSchemaEntryStore.ts— per-entry storage for registered schemasSchemaRefWalker.ts— walks schema$refchains to build resolution indexSchemaRegistry.ts—SchemaRegistryclass; registers, loads, and caches schemas
Module: transform (src/modules/transform/)
Transform.ts— encode and decode transform registry
Module: validation (src/modules/validation/)
Compiled validation. SchemaCompiler compiles graph nodes into executable validation plans.
Predicates.ts— primitive predicate functions for scalar, format, and type checksRefResolver.ts— resolves$refchains during compilationSchemaCompiler.ts— compiles graph nodes into validation plansSchemaCompilerDefaults.ts— default compiler option resolutionSchemaCompilerPlan.ts— builds the per-node validation plan structureSchemaCompilerSupport.ts— compiler utility functionsShaclValidator.ts— native SHACL validation engine; consumes SHACL shape quads fromShaclProjectionand ABox instance quads fromtoQuads(), returning a structured conformance report
Module: validation/exec (src/modules/validation/exec/)
Execution modules called by compiled validation plans.
Arrays.ts— array constraint executionComposition.ts— composition constraint executionObjects.ts— object constraint executionScalars.ts— scalar constraint execution
Module: viz (src/modules/viz/)
HTML rendering and visualization utilities.
HtmlRenderer.ts— renders schema graph as interactive HTMLTypeStringEmitter.ts— emits TypeScript type string representationsVizDataCollector.ts— collects graph data for visualization output