model-runtime
Use when loading a generated domain model (model.js from @jeswr/federation-codegen), calling defineModel on a shape-manifest, reading or writing pod RDF through generated entities, or changing the audited guard set in @jeswr/model-runtime.
- License 许可
- MIT
- 所属仓库
- jeswr/solid-sdk
- 最近更新
- 2026-11-15
- Stars
- ★ 2
- Forks
- 0
01 前言 Front Matter
- name
- model-runtime
- description
- Use when loading a generated domain model (model.js from @jeswr/federation-codegen), calling defineModel on a shape-manifest, reading or writing pod RDF through generated entities, or changing the audited guard set in @jeswr/model-runtime.
02 资源文件 33
- 许可证LICENSE1.0 KB
- 参考文档package.json1.7 KB
- 参考文档README.md18.4 KB
- 脚本src/aliases.test.ts23.1 KB
- 脚本src/composite.test.ts34.7 KB
- 脚本src/datatypes.ts28.3 KB
- 脚本src/datetime.test.ts22.2 KB
- 脚本src/guards.test.ts3.6 KB
- 脚本src/guards.ts8.0 KB
- 脚本src/index.ts2.2 KB
- 脚本src/manifest.test.ts3.8 KB
- 脚本src/manifest.ts34.5 KB
- 脚本src/model.test.ts14.3 KB
- 脚本src/model.ts60.8 KB
- 脚本src/parse-scope.test.ts14.6 KB
- 脚本src/parse-scope.ts5.9 KB
- 脚本src/phase-g.test.ts32.7 KB
- 脚本src/rdf.ts6.0 KB
- 脚本src/round10-review.test.ts7.9 KB
- 脚本src/round11-review.test.ts5.8 KB
- 脚本src/round12-review.test.ts6.1 KB
- 脚本src/round2-review.test.ts7.4 KB
- 脚本src/round3-review.test.ts7.9 KB
- 脚本src/round4-review.test.ts4.9 KB
- 脚本src/round5-review.test.ts11.3 KB
- 脚本src/round7-review.test.ts4.0 KB
- 脚本src/round8-review.test.ts9.5 KB
- 脚本src/round9-review.test.ts7.0 KB
- 脚本src/security-review.test.ts11.4 KB
- 脚本src/write-cost.test.ts6.1 KB
- 参考文档tsconfig.build.json118 B
- 参考文档tsconfig.json577 B
- 脚本vitest.config.ts156 B
03 SKILL.md 正文
<!-- AUTHORED-BY Codex GPT-6 --> <!-- AUTHORED-BY Codex (GPT-6.1 Sol) --> <!-- AUTHORED-BY Claude Opus 5.5 --> <!-- AUTHORED-BY Codex GPT-6 -->
Generated-model runtime
@jeswr/model-runtime lives in packages/model-runtime and is security-critical. It is the
one interpreter for every generated domain model: a generated model.js inlines a JSON
shape-manifest and calls defineModel(manifest); all behaviour lives here.
import model, { entities } from "./generated/model.js"; // emitted by federation-codegen
const bookmark = entities.Bookmark;
const store = bookmark.build(resourceUrl, { url: "https://example.org/a" }); // n3 Store
const data = bookmark.parse(resourceUrl, dataset); // object | undefined (fail-closed)
const ttl = await bookmark.serialize(resourceUrl, data); // n3.Writer Turtle
const parsed = await bookmark.parseDocument(resourceUrl, body, contentType); // via @jeswr/fetch-rdf
const w = new bookmark.Wrapper(bookmark.subject(resourceUrl), store, DataFactory);
Multi-subject scans should use a parse scope from @jeswr/model-runtime:
import { createParseScope } from "@jeswr/model-runtime";
const scope = createParseScope(dataset, { maxClassReads: 100_000 });
for (const url of resourceUrls) bookmark.parse(url, dataset, { scope });
if (scope.exhausted) throw new Error("Class scan budget exhausted");
The scope memoises membership by (class term, required-class set) and shares one raw
type/subclass read budget across all root and nested sh:class checks. The default is
100,000 reads; maxClassReads accepts integers 0–1,000,000 and rejects other values with
RangeError. Once another read would exceed the budget, scope.exhausted stays true and
all later class checks fail closed, including cached successes. Nested checks retain normal
required/optional grading. Reuse with another dataset throws TypeError.
Discard scopes after ANY dataset mutation; the memo is valid only for an unchanged dataset.
Build, setters, live sets and mark never consult scopes. Without parse(..., { scope }),
the existing per-check 10,000-read behavior is unchanged. parseDocument owns a new dataset
and does not accept a scope; scopes are for parse on existing datasets.
Rules
- Never hand-write a manifest for production use. Manifests come from
federation-codegen, whose fidelity assertion proves every field traces toshapes.ttlor the committed config. - Keep generated artifacts data-only. A manifest must never carry code, regex source,
templates or path expressions;
validateManifestrejects unknown keys and enforces caps. - All emission goes through
src/rdf.ts'sserializeTurtle, after alias migration. Immediately beforen3.Writer, reject unsafe NamedNodes in subject, predicate, object and graph positions, literal datatype IRIs, prefix namespaces, and prefix labels outside TurtlePN_PREFIX(the empty default prefix is allowed). Recheck mutable manifests; never escape or canonicalize an unsafe identity. Reject unsupported term kinds (including Variable/Quad), invalid RDF positions, invalid Turtle blank-node labels and malformed BCP 47 language tags. Re-parse buffered output and check the same quad set, including literal identity and a known blank-node bijection, before returning it; failure throwsTypeError. - Resource URLs and every derived subject pass
isSafeAbsoluteIriwithout rewriting their lexical identity.subject,build,serialize, and directWrapperconstruction throwTypeErroron an unsafe or relative IRI;parseandparseDocumentreturnundefined(before parsing an unsafe document base). Wrappers accept strings or safe absolute NamedNodes; other term kinds throwTypeError.storeToTurtlealso throwsTypeErrorfor unsafe NamedNodes and datatype IRIs anywhere in the emitted graph. Publictypes.addrejects unsafe IRIs before insertion. The exportedsubjectIri(resourceUrl, fragment?)validates both the resource and the minted subject; flat, composite, and generated per-node handles use it. Reject instead of escaping:rdf-serialize'sescapeIripercent-encodes forbidden characters and changes identity, whilen3.Writerdoes not validate IRIREF safety. - Every IRI field with
iriScheme: "http-https"oririScheme: "https"goes throughhttpIriOrUndefinedon read and write. On reads, first validate SHACL constraints on the original RDF term's exact lexical spelling; normalization only projects an already-admitted value. IRI enum members retain their exact identity on reads and writes; the scheme filter checks but never rewrites them. Do not widen schemes without a new reviewed guard. - A Violation-graded MUST (
requiredFailClosed) rejects the whole record on parse when missing, malformed, ambiguous, or outside its set cardinality bounds. At the root, optional fields drop and optional sets retain valid members. Nested validation checks all present values before projection. Required sets also reject any invalid raw member. - build does not enforce requiredFailClosed: missing or invalid values are dropped and a typed shell may be returned. This preserves the bookmark facade's write contract. Parse the built store and require a defined result before publishing it if MUST validation is needed.
- Closed
inenums are enforced on reads, build, setters and live-set adds. Invalid enum values drop, consistently with other invalid writes; they do not throw. Reads compare raw literal lexical forms and datatypes against canonical enum terms before mapping to JS values. Decimal/integer readers reject precision loss by comparing canonical decimal spellings before/after JS number conversion. String-subtype lexical validators run on raw values on reads and writes; never sanitize an invalid lexical form into a valid one. - Read aliases are optional
aliasTypeIrison flat entities/composite nodes and orderedaliasPredicateson flat fields (at most four distinct, Turtle-safe absolute http(s) IRIs per key). They exclude canonical IRIs; predicate aliases cannot overlap any canonical/alias predicate across the manifest. A canonical predicate shared across owners must have no aliases on any owner; co-typing means disjoint focus sets cannot be proved.rdf:typeand structural link predicates are reserved from flat fields and all aliases. Type aliases cannot overlap any canonical type or another owner's alias.nestedlinks reject aliases, including empty arrays. - Singleton reads guard the canonical value first, then aliases in order; only
undefinedfalls back (false,0, and""win). Defaults require all predicates to be absent, cannot satisfyrequiredFailClosed, and never apply withmaxCount: 0. Each predicate checks distinct raw terms and maxCount before mapping: ambiguity or a cardinality violation drops the field without alias fallback; a required field rejects. Sets expose the guarded union; parse checks raw-union maxCount and guarded raw-term-union minCount before deduplicating the JS projection. Required sets reject invalid raw members. Reads never mutate. Singleton migration preserves the raw term selected by canonical-first reads; set serialization and live-set mutations migrate all retained guard-passing raw terms. Keep exact lexical forms, datatypes, IRI spellings and raw cardinality, even for terms with equal JS projections. Revalidate raw terms, never re-project and rewrite retained values. Retained text is not sanitized during migration; explicitly supplied API values still pass through JS write guards and sanitization. Setters clear aliases even onundefined/invalid input;markclears explicit alias types. Serialization migrates aliases in a copy only at their owning shape's focus nodes: recognised entity roots (including data-graph subclasses) and composite nodes reached through bounded, unambiguous links satisfying explicit link classes. Determine all ownership against the original data before any mutation. Preserve unrelated subjects and unreached composite nodes, including their alias predicates/types. Preserve subclass type assertions and never add target types to untyped children during migration. - After serialization migration, re-parse every previously recognised entity and node
projection, including unreached typed nodes and reached untyped child focuses. Require
identical recognition and parsed results; throw exported
MigrationErrorbefore emission on any change, including an invalid-record repair or a newly exposed default. Bound all candidate scans, class walks and re-parse reads/visits with a shared 10,000 budget; exhaustion throws the same typed error. - Every write that can migrate aliases (build, singleton setters, live-set add/delete/clear,
mark(),storeToTurtle,serialize) runs the SAME checked migration on a copy BEFORE the explicit change; onMigrationErrorthe live dataset is unchanged. Setters/build/mark may skip the migration copy and audit only when the written field has no predicate aliases (or mark has no type aliases) AND no other owner in any migration-context manifest has aliases. This makes alias-free writes independent of unrelated dataset size without bypassing field guards or sanitization. Treat other owners conservatively: data-graph subclasses and co-typing prevent assuming disjoint focus nodes. Alias-bearing writes keep the existing audit, preservation checks and shared 10,000-read budget. Generated per-node views pass the owning manifest asdefineModel(views, { migrationManifest })so their checks see the full model. The primary manifest's own preservation checks always still run alongside, so the option can only add context, never drop a check. - Nested links carry their own
minCount, independent of root requiredness and severity: inside strictsh:nodevalidation an absent link below its minimum makes the child fail. Before deleting alias types, materialise satisfied explicit link classes on affected subjects, preserving ancestry proofs as builds do. - Deliberate G5 migration exception (root reads): for singleton
sh:alternativePathfields, SHACL counts the union formaxCount, but runtime reads resolve canonical-first. A stale conflicting alias beside a valid canonical value can therefore parse even when the emitted SHACL rejects that union's cardinality. This preserves the reviewed bookmark oracle. Writes are canonical-only and clear aliases, so the runtime never produces that conflicting data at the migrated field's focus nodes. - Composite entities graph-walk exact link terms from the root; never assume fragments. Count distinct raw object terms of every kind before filtering NamedNodes; more than one rejects a required link's record or drops an optional link's whole subtree. A linked NamedNode must be an absolute http(s) IRI without IRIREF-forbidden characters. Follow that exact term without URL canonicalisation; an unsafe required link rejects the record and an optional link drops its subtree.
- Retain a composite link's
sh:classashasClass. Check the linked subject's actualrdf:typevalues andrdfs:subClassOf*chains in the data graph, never the build-time ontology. Without a parse scope, bound traversal to 10,000 raw reads per link and track visited class terms; absence, cycles without membership, and budget exhaustion fail the link closed with its required/optional grading. Node-type recognition (flat entities, composite roots, and per-node wrappers) uses the same bounded walk to any canonical or alias target class, with one 10,000 raw-read budget across the accepted classes. Never add or delete subclassrdf:typeassertions during recognition or serialization;markretains its existing explicit alias-to-canonical type migration. Builds assert the explicit link class on materialised children. For composite children, validate the property constraints without requiring the child shape's target type:sh:targetClassselects focus nodes, whilesh:nodeapplies the child constraints directly. Every present child value must satisfy its property constraints, even optional fields or deeper optional links. Absent values obey the property's minimum. Check the raw path union for nested conformance before canonical-first projection. A failed child rejects a required incoming link or drops an optional root link's subtree. Root field parsing retains its drop-invalid-optional policy. ExplicithasClassstill applies.classOnly: truerecordssh:classwithoutsh:node; requirehasClassto equal the child's sole canonical target class exactly. The strict every-present-value rule applies tosh:nodechildren only. A class-only child is its own class-targeted focus node, so it parses with the root policy: its optional failures (ambiguous optional links, malformed optional values) drop only that field, and only its required fail-closed constraints reject it. Reject a link whosehasClassnames a type alias owned by ANY entity or node in the manifest, including optional links: type migration can delete that assertion. - Domain policy the schema cannot express (network fetches, SSRF policy, reconciliation) belongs in the consuming package's facade, not in this runtime.
- Changes here are security-critical: add an adversarial test that fails before the fix.
Exports
defineModel, createParseScope, ParseScope, ParseScopeOptions, ParseOptions,
validateManifest, ManifestError, MigrationError, MANIFEST_VERSION, RUNTIME_MAJOR,
manifest types, and the shared guards httpIriOrUndefined, isHttpIri, sanitizeText,
tryRead, isSafeAbsoluteIri, isTurtlePrefixName, subjectIri, the strict RDF/JS readLiteral reader, plus the XSD datatype
mappers. Packages migrating off hand-written models may reuse the guards so their filter
behaviour stays byte-identical.
04 同仓库更多 Skills
storage-conformance
Work on @jeswr/storage-conformance, the shared storage conformance suite package in the Solid SDK workspace.
fetch-rdf-engine-tests
Maintain fetch-rdf's real Node WASM parser integration tests without introducing a reverse engine dependency in fetch-rdf.
alpha
Use when checking fixtures, including folded YAML descriptions.
widget
Use when testing package skills: YAML quoting works.
web-seo
Use when improving technical and entity SEO for a modern personal, portfolio, documentation, or marketing site, including crawlable HTML, canonical metadata, sitemap and robots, Person/ProfilePage JSON-LD, Core Web Vitals, and honest ranking expectations.
solid-wac
Use when implementing or auditing Solid server WAC authorization, ACL creation and inheritance, auxiliary-resource escalation, method-to-mode mapping, 401 versus 403 challenges, WAC-Allow, or defensive typed ACL parsing with @solid/object and @rdfjs/wrapper.