@wazootech/worlds-sdk 0.11.4 → 0.11.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -143,6 +143,7 @@ for structured traversal and reasoning, powered by the zero-dependency
143
143
  | `@wazootech/worlds-sdk/search-index` | Search index interface and types |
144
144
  | `@wazootech/worlds-sdk/sparql-engine` | SPARQL engine interface |
145
145
  | `@wazootech/worlds-sdk/rdfjs` | In-memory `RdfjsQuadStore` and `RdfjsSearchIndex` |
146
+ | `@wazootech/worlds-sdk/shacl` | Checks a write against a world's SHACL shapes |
146
147
  | `@wazootech/worlds-sdk/ai-sdk` | Vercel AI SDK tool bindings |
147
148
 
148
149
  The SPARQL engine is the external
@@ -0,0 +1,101 @@
1
+ import { J as RdfjsStoreLike, U as TransactionContext, Y as Patch } from "./mod-CH7Hc3EE.js";
2
+ import * as rdfjs from "@rdfjs/types";
3
+ /** SHAPES_GRAPH is the named graph that holds a world's SHACL shapes. */
4
+ export declare const SHAPES_GRAPH = "https://wazoo.dev/ns/worlds#shapes";
5
+ /**
6
+ * ShaclSource reads a world as it is before a write. Return each quad in every
7
+ * graph it is stored in, inferred ones included. Once a call has found more than
8
+ * `limit` quads it may stop: the check is refused either way.
9
+ */
10
+ interface ShaclSource {
11
+ /** shapes returns the quads in {@link SHAPES_GRAPH}. */
12
+ shapes(): Promise<rdfjs.Quad[]>;
13
+ /** outgoing returns the facts of these subjects, all of them or only some properties. */
14
+ outgoing(request: {
15
+ subjects: rdfjs.Term[];
16
+ predicates?: string[];
17
+ limit: number;
18
+ }): Promise<rdfjs.Quad[]>;
19
+ /** incoming returns the facts with this property whose object is one of these. */
20
+ incoming(request: {
21
+ objects: rdfjs.Term[];
22
+ predicate: string;
23
+ limit: number;
24
+ }): Promise<rdfjs.Quad[]>;
25
+ }
26
+ /** createRdfjsShaclSource reads from an RDF/JS store, one pattern at a time. */
27
+ export declare function createRdfjsShaclSource(store: Pick<RdfjsStoreLike, "match">): ShaclSource;
28
+ /** DEFAULT_MAX_CHECKED_FACTS is how many stored quads one check may read by default. */
29
+ export declare const DEFAULT_MAX_CHECKED_FACTS = 50000;
30
+ /** ValidateWriteRequest describes a write that hasn't happened yet. */
31
+ interface ValidateWriteRequest {
32
+ /** patch is what the write adds and removes. */
33
+ patch: Patch;
34
+ /** context says whether the write replaces everything that is stored. */
35
+ context?: TransactionContext;
36
+ /** source reads the world as it is before the write. */
37
+ source: ShaclSource;
38
+ /** maxCheckedFacts is how many stored quads the check may read. */
39
+ maxCheckedFacts?: number;
40
+ }
41
+ /**
42
+ * validateWrite rejects when a write would add new violations of the world's own
43
+ * shapes, which are the quads in {@link SHAPES_GRAPH}. Call it before writing.
44
+ *
45
+ * It checks only the nodes the write can affect, and reads only the facts those
46
+ * checks look at. A violation is new when the checked node didn't have it before, so
47
+ * shapes can be added to a world whose data breaks them. Linking another node to
48
+ * one that is broken gives the linking node a new violation.
49
+ *
50
+ * A world without shapes costs one read. A change to the class tree
51
+ * (`rdfs:subClassOf`) is treated like a change to the shapes: it applies to later
52
+ * writes and doesn't check existing nodes.
53
+ *
54
+ * @throws {ShaclViolationError} when the write adds violations.
55
+ * @throws {InvalidShapesError} when the shapes themselves can't be used.
56
+ * @throws {ShaclLimitError} when the check would read too much.
57
+ */
58
+ export declare function validateWrite(request: ValidateWriteRequest): Promise<void>;
59
+ /** ShaclViolation is one way in which a write would break a world's shapes. */
60
+ interface ShaclViolation {
61
+ /** focusNode is the node that breaks the shape: an IRI, a `_:` label or a literal's text. */
62
+ focusNode: string;
63
+ /** path is the checked property, written like a SPARQL path without angle brackets. */
64
+ path?: string;
65
+ /** value is the offending value, when one value is to blame. */
66
+ value?: string;
67
+ /** constraint is the local name of the broken constraint, such as `MaxCount`. */
68
+ constraint: string;
69
+ /** shape is the IRI of the broken shape; absent when the shape has none. */
70
+ shape?: string;
71
+ /** message is the shape's `sh:message`, or a description of the constraint. */
72
+ message: string;
73
+ }
74
+ /** ShaclViolationError rejects a write that would add new violations. Nothing was written. */
75
+ export declare class ShaclViolationError extends Error {
76
+ /** violations are the new violations, in no particular order. */
77
+ readonly violations: ShaclViolation[];
78
+ readonly name = "ShaclViolationError";
79
+ constructor(
80
+ /** violations are the new violations, in no particular order. */
81
+ violations: ShaclViolation[]);
82
+ }
83
+ /** InvalidShapesError rejects a write because the world's shapes can't be used. Nothing was written. */
84
+ export declare class InvalidShapesError extends Error {
85
+ /** problems say what is wrong with the shapes, one sentence each. */
86
+ readonly problems: string[];
87
+ readonly name = "InvalidShapesError";
88
+ constructor(
89
+ /** problems say what is wrong with the shapes, one sentence each. */
90
+ problems: string[]);
91
+ }
92
+ /** ShaclLimitError rejects a write whose check would read too many facts. Nothing was written. */
93
+ export declare class ShaclLimitError extends Error {
94
+ /** limit is how many facts one check may read. */
95
+ readonly limit: number;
96
+ readonly name = "ShaclLimitError";
97
+ constructor(
98
+ /** limit is how many facts one check may read. */
99
+ limit: number);
100
+ }
101
+ export type { ShaclSource, ShaclViolation, ValidateWriteRequest };
package/dist/shacl.js ADDED
@@ -0,0 +1,961 @@
1
+ import { x as isReplaceImportCommit } from "./quad-store-oBgXOONP.js";
2
+ import { r as collectQuadsFromStream } from "./rdf-formats-C2znopLM.js";
3
+ import { RE2JS } from "re2js";
4
+ import { DataFactory } from "@wazootech/sparql-engine/data-model";
5
+ import SHACLValidator from "rdf-validate-shacl";
6
+ // src/shacl/vocabulary.ts
7
+ /** SHAPES_GRAPH is the named graph that holds a world's SHACL shapes. */
8
+ const SHAPES_GRAPH = "https://wazoo.dev/ns/worlds#shapes";
9
+ /** SH is the namespace of SHACL. */
10
+ const SH = "http://www.w3.org/ns/shacl#";
11
+ const RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#";
12
+ const RDFS = "http://www.w3.org/2000/01/rdf-schema#";
13
+ const RDF_TYPE = `${RDF}type`;
14
+ const RDF_FIRST = `${RDF}first`;
15
+ const RDF_REST = `${RDF}rest`;
16
+ const RDF_NIL = `${RDF}nil`;
17
+ const RDFS_SUBCLASS_OF = `${RDFS}subClassOf`;
18
+ /** SHAPE_LINKS are the parameters whose value is another shape. */
19
+ const SHAPE_LINKS = [
20
+ "property",
21
+ "node",
22
+ "not",
23
+ "qualifiedValueShape"
24
+ ];
25
+ /** SHAPE_LISTS are the parameters whose value is a list of other shapes. */
26
+ const SHAPE_LISTS = [
27
+ "and",
28
+ "or",
29
+ "xone"
30
+ ];
31
+ /** COMPARED_PROPERTIES are the parameters that read another property of the focus node. */
32
+ const COMPARED_PROPERTIES = [
33
+ "equals",
34
+ "disjoint",
35
+ "lessThan",
36
+ "lessThanOrEquals"
37
+ ];
38
+ // src/shacl/triple-index.ts
39
+ /** termKey identifies a term by its type and value, datatype and language included. */
40
+ function termKey(term) {
41
+ switch (term.termType) {
42
+ case "Literal": return `"${term.datatype.value} ${term.language} ${term.value}`;
43
+ case "Quad": return `<<${tripleKey(term)}`;
44
+ default: return `${term.termType[0]}${term.value}`;
45
+ }
46
+ }
47
+ /** tripleKey identifies a quad without its graph. */
48
+ function tripleKey(quad) {
49
+ return JSON.stringify([
50
+ termKey(quad.subject),
51
+ quad.predicate.value,
52
+ termKey(quad.object)
53
+ ]);
54
+ }
55
+ /**
56
+ * TripleIndex is an RDF/JS dataset that looks facts up by subject or object and
57
+ * ignores graphs. SHACL checks one graph, so a fact stated in two counts once.
58
+ */
59
+ var TripleIndex = class TripleIndex {
60
+ triples = /* @__PURE__ */ new Map();
61
+ bySubject = /* @__PURE__ */ new Map();
62
+ byObject = /* @__PURE__ */ new Map();
63
+ constructor(quads = []) {
64
+ for (const quad of quads) this.add(quad);
65
+ }
66
+ get size() {
67
+ return this.triples.size;
68
+ }
69
+ add(quad) {
70
+ const key = tripleKey(quad);
71
+ if (this.triples.has(key)) return this;
72
+ this.triples.set(key, quad);
73
+ file(this.bySubject, termKey(quad.subject), quad);
74
+ file(this.byObject, termKey(quad.object), quad);
75
+ return this;
76
+ }
77
+ has(quad) {
78
+ return this.triples.has(tripleKey(quad));
79
+ }
80
+ delete(quad) {
81
+ const key = tripleKey(quad);
82
+ const stored = this.triples.get(key);
83
+ if (stored === void 0) return this;
84
+ this.triples.delete(key);
85
+ const name = stored.predicate.value;
86
+ this.bySubject.get(termKey(stored.subject))?.get(name)?.delete(stored);
87
+ this.byObject.get(termKey(stored.object))?.get(name)?.delete(stored);
88
+ return this;
89
+ }
90
+ match(subject, predicate, object) {
91
+ return new TripleIndex(this.find(subject, predicate, object));
92
+ }
93
+ /** find returns the facts that match, without building an index of them. */
94
+ find(subject, predicate, object) {
95
+ let candidates = this.triples.values();
96
+ if (subject) candidates = lookUp(this.bySubject, subject, predicate);
97
+ else if (object) candidates = lookUp(this.byObject, object, predicate);
98
+ const found = [];
99
+ for (const quad of candidates) {
100
+ if (predicate && quad.predicate.value !== predicate.value) continue;
101
+ if (subject && object && !quad.object.equals(object)) continue;
102
+ found.push(quad);
103
+ }
104
+ return found;
105
+ }
106
+ [Symbol.iterator]() {
107
+ return this.triples.values();
108
+ }
109
+ };
110
+ function file(index, key, quad) {
111
+ let byPredicate = index.get(key);
112
+ if (!byPredicate) index.set(key, byPredicate = /* @__PURE__ */ new Map());
113
+ const quads = byPredicate.get(quad.predicate.value);
114
+ if (quads) quads.add(quad);
115
+ else byPredicate.set(quad.predicate.value, /* @__PURE__ */ new Set([quad]));
116
+ }
117
+ function lookUp(index, term, predicate) {
118
+ const byPredicate = index.get(termKey(term));
119
+ if (!byPredicate) return [];
120
+ if (predicate) return byPredicate.get(predicate.value) ?? [];
121
+ return [...byPredicate.values()].flatMap((quads) => [...quads]);
122
+ }
123
+ // src/shacl/affected-nodes.ts
124
+ /**
125
+ * findAffectedNodes starts at each changed fact and follows the shapes' reads
126
+ * backwards to the nodes that see it. The facts after the write are enough for
127
+ * that: whatever a node sees differently, the first changed fact on the way to it
128
+ * is reached over facts the write didn't change. It keeps the nodes a shape
129
+ * applies to after the write, as one it no longer applies to can't have a violation.
130
+ */
131
+ function findAffectedNodes(changed, targets, after) {
132
+ return targets.flatMap((target) => {
133
+ const nodes = /* @__PURE__ */ new Map();
134
+ for (const read of target.reads) for (const node of followBack(startNodes(changed, read), read.via, after)) nodes.set(termKey(node), node);
135
+ return [...nodes.values()].filter((node) => after.isTarget(node, target)).map((node) => ({
136
+ node,
137
+ target
138
+ }));
139
+ });
140
+ }
141
+ /** startNodes are the nodes at which a read finds one of the changed facts. */
142
+ function startNodes(changed, read) {
143
+ return changed.filter((quad) => (read.predicate ?? quad.predicate.value) === quad.predicate.value).map((quad) => read.inverse ? quad.object : quad.subject);
144
+ }
145
+ function followBack(start, via, after) {
146
+ let nodes = unique(start);
147
+ for (const step of [...via].reverse()) nodes = unique(nodes.flatMap((node) => step.inverse ? after.outgoing(node, step.predicate) : after.incoming(node, step.predicate)));
148
+ return nodes;
149
+ }
150
+ function unique(nodes) {
151
+ return [...new Map(nodes.map((node) => [termKey(node), node])).values()];
152
+ }
153
+ // src/shacl/shacl-errors.ts
154
+ /** ShaclViolationError rejects a write that would add new violations. Nothing was written. */
155
+ var ShaclViolationError = class extends Error {
156
+ violations;
157
+ name = "ShaclViolationError";
158
+ constructor(violations) {
159
+ const [first] = violations;
160
+ const more = violations.length > 1 ? ` (and ${violations.length - 1} more)` : "";
161
+ const where = first?.path ? `${first.focusNode} ${first.path}` : first?.focusNode;
162
+ super(`The write breaks the world's shapes: ${where}: ${first?.message}${more}`);
163
+ this.violations = violations;
164
+ }
165
+ };
166
+ /** InvalidShapesError rejects a write because the world's shapes can't be used. Nothing was written. */
167
+ var InvalidShapesError = class extends Error {
168
+ problems;
169
+ name = "InvalidShapesError";
170
+ constructor(problems) {
171
+ super(`The world's shapes can't be used: ${problems.join(" ")}`);
172
+ this.problems = problems;
173
+ }
174
+ };
175
+ /** ShaclLimitError rejects a write whose check would read too many facts. Nothing was written. */
176
+ var ShaclLimitError = class extends Error {
177
+ limit;
178
+ name = "ShaclLimitError";
179
+ constructor(limit) {
180
+ super(`Checking this write against the world's shapes needs more than ${limit} facts.`);
181
+ this.limit = limit;
182
+ }
183
+ };
184
+ // src/shacl/safe-pattern.ts
185
+ const FLAGS = {
186
+ i: RE2JS.CASE_INSENSITIVE,
187
+ s: RE2JS.DOTALL,
188
+ m: RE2JS.MULTILINE
189
+ };
190
+ /**
191
+ * compilePattern prepares an `sh:pattern` for matching in time that grows with
192
+ * the length of the text only. JavaScript's own matcher can take hours on a short
193
+ * text with a pattern such as `^(a+)+$`, and nothing can interrupt it. In return,
194
+ * look-ahead, look-behind and back-references are not supported.
195
+ *
196
+ * @throws when the pattern or a flag isn't supported.
197
+ */
198
+ function compilePattern(pattern, flags = "") {
199
+ let options = 0;
200
+ for (const flag of flags) {
201
+ const option = FLAGS[flag];
202
+ if (option === void 0) throw new Error(`the flag "${flag}" is not supported`);
203
+ options |= option;
204
+ }
205
+ const compiled = RE2JS.compile(RE2JS.translateRegExp(pattern), options);
206
+ return (text) => compiled.matcher(text).find();
207
+ }
208
+ // src/shacl/shape-graph.ts
209
+ /** ShapeGraph reads a shapes graph by SHACL term name. */
210
+ var ShapeGraph = class {
211
+ index;
212
+ constructor(quads) {
213
+ this.index = new TripleIndex(quads);
214
+ }
215
+ /** values returns the objects of a node's `sh:` property. */
216
+ values(node, name) {
217
+ return this.objects(node, SH + name);
218
+ }
219
+ /** objects returns the objects of any property, named by IRI. */
220
+ objects(node, predicate) {
221
+ return this.index.find(node).filter((quad) => quad.predicate.value === predicate).map((quad) => quad.object);
222
+ }
223
+ /** isTrue says whether a node's boolean `sh:` property is set to `true`. */
224
+ isTrue(node, name) {
225
+ return this.values(node, name).some((value) => value.value === "true");
226
+ }
227
+ /** isDefined says whether the graph says anything about a node. */
228
+ isDefined(node) {
229
+ return this.index.find(node).length > 0;
230
+ }
231
+ /** list returns an RDF list's members, or undefined when it isn't a proper list. */
232
+ list(head) {
233
+ const members = [];
234
+ const seen = /* @__PURE__ */ new Set();
235
+ let cell = head;
236
+ while (cell.value !== RDF_NIL) {
237
+ const first = this.objects(cell, RDF_FIRST);
238
+ const rest = this.objects(cell, RDF_REST);
239
+ if (first.length !== 1 || rest.length !== 1) return void 0;
240
+ if (seen.has(cell.value)) return void 0;
241
+ seen.add(cell.value);
242
+ members.push(first[0]);
243
+ cell = rest[0];
244
+ }
245
+ return members;
246
+ }
247
+ };
248
+ // src/shacl/shape-path.ts
249
+ /** MAX_ROUTES is how many ways one path may be followed. */
250
+ const MAX_ROUTES = 100;
251
+ /** UnsupportedPathError says why a path can't be used in a shape. */
252
+ var UnsupportedPathError = class extends Error {};
253
+ /**
254
+ * expandPath lists the ways to follow a SHACL property path, each as a sequence
255
+ * of steps. Alternatives and optional steps become separate routes. A path that
256
+ * repeats without end has no such list, so it is refused.
257
+ */
258
+ function expandPath(path, shapes, depth = 0) {
259
+ if (path.termType === "NamedNode") return [[{
260
+ predicate: path.value,
261
+ inverse: false
262
+ }]];
263
+ if (path.termType !== "BlankNode") throw new UnsupportedPathError("A path must be an IRI or a path expression.");
264
+ if (depth > 20) throw new UnsupportedPathError("A path is nested too deeply.");
265
+ if (shapes.objects(path, "http://www.w3.org/1999/02/22-rdf-syntax-ns#first").length > 0) return members(path, shapes).reduce((routes, member) => join(routes, expandPath(member, shapes, depth + 1)), [[]]);
266
+ for (const endless of ["zeroOrMorePath", "oneOrMorePath"]) if (shapes.values(path, endless).length > 0) throw new UnsupportedPathError(`Worlds does not support sh:${endless}.`);
267
+ const [inverse] = shapes.values(path, "inversePath");
268
+ if (inverse) {
269
+ if (inverse.termType !== "NamedNode") throw new UnsupportedPathError("sh:inversePath must name one property.");
270
+ return [[{
271
+ predicate: inverse.value,
272
+ inverse: true
273
+ }]];
274
+ }
275
+ const [optional] = shapes.values(path, "zeroOrOnePath");
276
+ if (optional) return [[], ...expandPath(optional, shapes, depth + 1)];
277
+ const [alternatives] = shapes.values(path, "alternativePath");
278
+ if (alternatives) return limit(members(alternatives, shapes).flatMap((member) => expandPath(member, shapes, depth + 1)));
279
+ throw new UnsupportedPathError("A path expression is empty.");
280
+ }
281
+ /** formatPath writes the routes of a path the way SPARQL would. */
282
+ function formatPath(routes) {
283
+ return routes.filter((steps) => steps.length > 0).map((steps) => steps.map((step) => step.inverse ? `^${step.predicate}` : step.predicate).join("/")).join("|");
284
+ }
285
+ function members(head, shapes) {
286
+ const list = shapes.list(head);
287
+ if (list === void 0 || list.length === 0) throw new UnsupportedPathError("A path has a broken or empty list.");
288
+ return list;
289
+ }
290
+ function join(left, right) {
291
+ return limit(left.flatMap((start) => right.map((end) => [...start, ...end])));
292
+ }
293
+ function limit(routes) {
294
+ if (routes.length <= MAX_ROUTES) return routes;
295
+ throw new UnsupportedPathError(`A path has more than ${MAX_ROUTES} routes.`);
296
+ }
297
+ // src/shacl/shape-reads.ts
298
+ /** MAX_READS is how many kinds of fact one shape may depend on. */
299
+ const MAX_READS = 1e3;
300
+ /** UnsupportedShapeError says why a shape can't be checked on every write. */
301
+ var UnsupportedShapeError = class extends Error {};
302
+ /**
303
+ * collectReads works out every kind of fact a shape depends on, through the
304
+ * shapes it refers to. Following them backwards from a changed fact finds the
305
+ * nodes to check again, so a missing read here would let a bad write through.
306
+ */
307
+ function collectReads(shapes, root) {
308
+ const reads = /* @__PURE__ */ new Map();
309
+ let visits = 0;
310
+ function add(via, predicate, inverse = false) {
311
+ reads.set(JSON.stringify([
312
+ via,
313
+ predicate,
314
+ inverse
315
+ ]), {
316
+ via,
317
+ predicate,
318
+ inverse
319
+ });
320
+ }
321
+ function addCompared(shape, via) {
322
+ for (const name of COMPARED_PROPERTIES) for (const other of shapes.values(shape, name)) add(via, other.value);
323
+ }
324
+ function visit(shape, via, open) {
325
+ const key = termKey(shape);
326
+ if (open.includes(key)) throw new UnsupportedShapeError("A shape refers to itself.");
327
+ if (++visits > MAX_READS || reads.size > MAX_READS) throw new UnsupportedShapeError("A shape is too complex.");
328
+ const [path] = shapes.values(shape, "path");
329
+ const routes = path ? expandPath(path, shapes) : [[]];
330
+ for (const steps of routes) steps.forEach((step, index) => add([...via, ...steps.slice(0, index)], step.predicate, step.inverse));
331
+ addCompared(shape, via);
332
+ const children = childShapes(shapes, shape);
333
+ for (const steps of routes) {
334
+ const values = [...via, ...steps];
335
+ if (shapes.values(shape, "class").length > 0) add(values, RDF_TYPE);
336
+ if (shapes.isTrue(shape, "closed")) add(values);
337
+ for (const child of children) visit(child, values, [...open, key]);
338
+ for (const head of path ? shapes.values(shape, "and") : []) for (const child of shapes.list(head) ?? []) addCompared(child, via);
339
+ }
340
+ }
341
+ visit(root, [], []);
342
+ return [...reads.values()];
343
+ }
344
+ /** childShapes lists the shapes that a shape applies to its value nodes. */
345
+ function childShapes(shapes, shape) {
346
+ return [
347
+ ...SHAPE_LINKS.flatMap((name) => shapes.values(shape, name)),
348
+ ...SHAPE_LISTS.flatMap((name) => shapes.values(shape, name)).flatMap((head) => shapes.list(head) ?? []),
349
+ ...siblingValueShapes(shapes, shape)
350
+ ];
351
+ }
352
+ /** siblingValueShapes are the shapes `sh:qualifiedValueShapesDisjoint` also checks. */
353
+ function siblingValueShapes(shapes, shape) {
354
+ if (!shapes.isTrue(shape, "qualifiedValueShapesDisjoint")) return [];
355
+ const own = shapes.values(shape, "qualifiedValueShape");
356
+ return shapes.index.find(null, null, shape).filter((quad) => quad.predicate.value.endsWith("#property")).flatMap((quad) => shapes.values(quad.subject, "property")).flatMap((sibling) => shapes.values(sibling, "qualifiedValueShape")).filter((sibling) => !own.some((term) => term.equals(sibling)));
357
+ }
358
+ // src/shacl/shape-rules.ts
359
+ const isIri = (value) => value.termType === "NamedNode";
360
+ const isLiteral = (value) => value.termType === "Literal";
361
+ const iri = {
362
+ accepts: isIri,
363
+ expected: "an IRI"
364
+ };
365
+ const text = {
366
+ accepts: isLiteral,
367
+ expected: "a literal"
368
+ };
369
+ const anything = {};
370
+ const list = { single: true };
371
+ const count = {
372
+ single: true,
373
+ accepts: (value) => isLiteral(value) && /^\d+$/.test(value.value),
374
+ expected: "a whole number"
375
+ };
376
+ const flag = {
377
+ single: true,
378
+ accepts: (value) => isLiteral(value) && ["true", "false"].includes(value.value),
379
+ expected: "true or false"
380
+ };
381
+ /** oneOf accepts the named SHACL terms only. */
382
+ function oneOf(...names) {
383
+ return {
384
+ single: true,
385
+ accepts: (value) => isIri(value) && names.includes(localName(value.value)),
386
+ expected: names.map((name) => `sh:${name}`).join(" or ")
387
+ };
388
+ }
389
+ /** localName is the part of a SHACL IRI after its namespace. */
390
+ function localName(name) {
391
+ return name.slice(name.indexOf("#") + 1);
392
+ }
393
+ /** SHAPE_RULES lists every SHACL property that Worlds accepts in a shapes graph. */
394
+ const SHAPE_RULES = {
395
+ targetClass: iri,
396
+ targetNode: anything,
397
+ targetSubjectsOf: iri,
398
+ targetObjectsOf: iri,
399
+ path: { single: true },
400
+ inversePath: { single: true },
401
+ alternativePath: list,
402
+ zeroOrOnePath: { single: true },
403
+ property: anything,
404
+ node: anything,
405
+ not: anything,
406
+ and: anything,
407
+ or: anything,
408
+ xone: anything,
409
+ qualifiedValueShape: {
410
+ single: true,
411
+ needsPath: true
412
+ },
413
+ deactivated: flag,
414
+ severity: oneOf("Violation", "Warning", "Info"),
415
+ class: iri,
416
+ closed: flag,
417
+ datatype: {
418
+ ...iri,
419
+ single: true
420
+ },
421
+ disjoint: iri,
422
+ equals: iri,
423
+ flags: {
424
+ ...text,
425
+ single: true
426
+ },
427
+ hasValue: anything,
428
+ ignoredProperties: list,
429
+ in: list,
430
+ languageIn: list,
431
+ lessThan: {
432
+ ...iri,
433
+ needsPath: true
434
+ },
435
+ lessThanOrEquals: {
436
+ ...iri,
437
+ needsPath: true
438
+ },
439
+ maxCount: {
440
+ ...count,
441
+ needsPath: true
442
+ },
443
+ maxExclusive: {
444
+ ...text,
445
+ single: true
446
+ },
447
+ maxInclusive: {
448
+ ...text,
449
+ single: true
450
+ },
451
+ maxLength: count,
452
+ minCount: {
453
+ ...count,
454
+ needsPath: true
455
+ },
456
+ minExclusive: {
457
+ ...text,
458
+ single: true
459
+ },
460
+ minInclusive: {
461
+ ...text,
462
+ single: true
463
+ },
464
+ minLength: count,
465
+ nodeKind: oneOf("IRI", "BlankNode", "Literal", "BlankNodeOrIRI", "BlankNodeOrLiteral", "IRIOrLiteral"),
466
+ pattern: {
467
+ ...text,
468
+ single: true
469
+ },
470
+ qualifiedMaxCount: {
471
+ ...count,
472
+ needsPath: true
473
+ },
474
+ qualifiedMinCount: {
475
+ ...count,
476
+ needsPath: true
477
+ },
478
+ qualifiedValueShapesDisjoint: {
479
+ ...flag,
480
+ needsPath: true
481
+ },
482
+ uniqueLang: {
483
+ ...flag,
484
+ needsPath: true
485
+ },
486
+ message: text,
487
+ name: text,
488
+ description: text,
489
+ order: anything,
490
+ group: anything,
491
+ defaultValue: anything,
492
+ declare: anything,
493
+ prefix: anything,
494
+ namespace: anything
495
+ };
496
+ /** SHAPE_TYPES are the SHACL classes a node in a shapes graph may have. */
497
+ const SHAPE_TYPES = [
498
+ "NodeShape",
499
+ "PropertyShape",
500
+ "PropertyGroup",
501
+ "PrefixDeclaration"
502
+ ];
503
+ // src/shacl/shape-target.ts
504
+ /** TARGETS are the properties that make a shape apply to nodes by itself. */
505
+ const TARGETS = [
506
+ "targetClass",
507
+ "targetNode",
508
+ "targetSubjectsOf",
509
+ "targetObjectsOf"
510
+ ].map((name) => SH + name);
511
+ /** findTargets lists the active shapes that have a target. */
512
+ function findTargets(shapes) {
513
+ const nodes = /* @__PURE__ */ new Map();
514
+ for (const quad of shapes.index) {
515
+ const { subject, predicate, object } = quad;
516
+ if (TARGETS.includes(predicate.value) || isClassShape(shapes, object, quad)) nodes.set(termKey(subject), subject);
517
+ }
518
+ return [...nodes.values()].filter((shape) => !shapes.isTrue(shape, "deactivated")).map((shape) => readTarget(shapes, shape));
519
+ }
520
+ /** isClassShape recognizes a shape that is also a class, which targets its instances. */
521
+ function isClassShape(shapes, type, quad) {
522
+ return quad.predicate.value === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && type.value === "http://www.w3.org/2000/01/rdf-schema#Class" && shapes.index.find(quad.subject).some((other) => other.predicate.value.startsWith("http://www.w3.org/ns/shacl#"));
523
+ }
524
+ function readTarget(shapes, shape) {
525
+ const classes = shapes.values(shape, "targetClass");
526
+ if (shapes.objects(shape, "http://www.w3.org/1999/02/22-rdf-syntax-ns#type").some((type) => type.value === "http://www.w3.org/2000/01/rdf-schema#Class")) classes.push(shape);
527
+ const iris = (name) => shapes.values(shape, name).map((term) => term.value);
528
+ const subjectsOf = iris("targetSubjectsOf");
529
+ const objectsOf = iris("targetObjectsOf");
530
+ const here = (predicate, inverse) => ({
531
+ via: [],
532
+ predicate,
533
+ inverse
534
+ });
535
+ return {
536
+ shape,
537
+ classes,
538
+ nodes: new Set(shapes.values(shape, "targetNode").map(termKey)),
539
+ subjectsOf,
540
+ objectsOf,
541
+ reads: [
542
+ ...classes.length > 0 ? [here(RDF_TYPE, false)] : [],
543
+ ...subjectsOf.map((predicate) => here(predicate, false)),
544
+ ...objectsOf.map((predicate) => here(predicate, true)),
545
+ ...collectReads(shapes, shape)
546
+ ]
547
+ };
548
+ }
549
+ // src/shacl/compile-shapes.ts
550
+ /** LISTS are the properties whose value is an RDF list. */
551
+ const LISTS = [
552
+ ...SHAPE_LISTS,
553
+ "in",
554
+ "languageIn",
555
+ "ignoredProperties"
556
+ ];
557
+ /**
558
+ * compileShapes checks a shapes graph and works out what each shape reads. SHACL
559
+ * ignores a misspelled property, and a validator may stop on one it doesn't know.
560
+ * Both are refused here, when the shapes are written, so that a shape is either
561
+ * enforced on every later write or never stored.
562
+ *
563
+ * @throws {InvalidShapesError} when a shape can't be enforced.
564
+ */
565
+ function compileShapes(quads) {
566
+ const graph = new ShapeGraph(quads);
567
+ const problems = /* @__PURE__ */ new Set();
568
+ for (const quad of graph.index) for (const problem of checkQuad(graph, quad)) problems.add(problem);
569
+ for (const shape of shapesIn(graph)) for (const problem of attempt(() => collectReads(graph, shape))) problems.add(problem);
570
+ if (problems.size > 0) throw new InvalidShapesError([...problems]);
571
+ return {
572
+ graph,
573
+ targets: findTargets(graph)
574
+ };
575
+ }
576
+ /** shapesIn lists the nodes with a SHACL property, each once. */
577
+ function shapesIn(graph) {
578
+ const shapes = /* @__PURE__ */ new Map();
579
+ for (const { subject, predicate } of graph.index) if (predicate.value.startsWith("http://www.w3.org/ns/shacl#")) shapes.set(termKey(subject), subject);
580
+ return shapes.values();
581
+ }
582
+ function* checkQuad(graph, quad) {
583
+ const { subject, predicate, object } = quad;
584
+ if (predicate.value === "http://www.w3.org/2002/07/owl#imports") yield "owl:imports is not supported: add the imported shapes to the graph.";
585
+ if (predicate.value === "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" && object.value.startsWith("http://www.w3.org/ns/shacl#")) {
586
+ const type = localName(object.value);
587
+ if (!SHAPE_TYPES.includes(type)) yield `sh:${type} is not supported.`;
588
+ }
589
+ if (!predicate.value.startsWith("http://www.w3.org/ns/shacl#")) return;
590
+ const name = localName(predicate.value);
591
+ const rule = Object.hasOwn(SHAPE_RULES, name) ? SHAPE_RULES[name] : void 0;
592
+ if (!rule) {
593
+ yield `sh:${name} is not supported.`;
594
+ return;
595
+ }
596
+ const where = describe(subject);
597
+ if (rule.accepts && !rule.accepts(object)) yield `sh:${name} must be ${rule.expected}${where}.`;
598
+ if (rule.single && graph.values(subject, name).length > 1) yield `sh:${name} is set more than once${where}.`;
599
+ if (rule.needsPath && graph.values(subject, "path").length === 0) yield `sh:${name} needs an sh:path${where}.`;
600
+ yield* checkValue(graph, quad, name, where);
601
+ }
602
+ function* checkValue(graph, { subject, object }, name, where) {
603
+ const children = SHAPE_LINKS.includes(name) ? [object] : [];
604
+ if (LISTS.includes(name)) {
605
+ const members = graph.list(object);
606
+ if (!members) yield `sh:${name} must be a list${where}.`;
607
+ if (SHAPE_LISTS.includes(name)) children.push(...members ?? []);
608
+ }
609
+ for (const child of children) if (!graph.isDefined(child)) yield `sh:${name} refers to ${child.value}, which has no definition.`;
610
+ const hasPath = (shape) => graph.values(shape, "path").length > 0;
611
+ if (name === "property" && !hasPath(object)) yield `sh:property needs a shape with an sh:path${where}.`;
612
+ if (name === "and" && hasPath(subject) && children.some(hasPath)) yield `sh:and can't hold property shapes when it has an sh:path itself${where}.`;
613
+ if (name === "path") yield* attempt(() => expandPath(object, graph));
614
+ if (name === "pattern") {
615
+ const [flags] = graph.values(subject, "flags");
616
+ yield* attempt(() => compilePattern(object.value, flags?.value), `sh:pattern "${object.value}" can't be used: `);
617
+ }
618
+ }
619
+ /** attempt turns an exception into a problem. */
620
+ function* attempt(action, prefix = "") {
621
+ try {
622
+ action();
623
+ } catch (error) {
624
+ yield `${prefix}${(error instanceof Error ? error.message : String(error)).replace(/\.?$/, ".")}`;
625
+ }
626
+ }
627
+ function describe(node) {
628
+ return node.termType === "NamedNode" ? ` (on ${node.value})` : "";
629
+ }
630
+ // src/shacl/world-state.ts
631
+ /**
632
+ * WorldState is the part of a world that a check has loaded, either as it was
633
+ * before the write or as it would be after. Asking for facts that aren't loaded
634
+ * returns nothing and notes them in {@link LoadedFacts}, so the caller can load
635
+ * them and ask again.
636
+ */
637
+ var WorldState = class {
638
+ loaded;
639
+ facts = new TripleIndex();
640
+ constructor(loaded) {
641
+ this.loaded = loaded;
642
+ }
643
+ get size() {
644
+ return this.facts.size;
645
+ }
646
+ add(quad) {
647
+ this.facts.add(quad);
648
+ return this;
649
+ }
650
+ delete() {
651
+ throw new Error("A check never removes facts from a state.");
652
+ }
653
+ has(quad) {
654
+ return this.match(quad.subject, quad.predicate, quad.object).size > 0;
655
+ }
656
+ match(subject, predicate, object) {
657
+ return new TripleIndex(this.find(subject, predicate, object));
658
+ }
659
+ /** outgoing returns the objects of a node's property. */
660
+ outgoing(node, predicate) {
661
+ this.loaded.needOutgoing(node);
662
+ return this.facts.find(node, DataFactory.namedNode(predicate)).map((quad) => quad.object);
663
+ }
664
+ /** incoming returns the nodes whose property has this node as a value. */
665
+ incoming(node, predicate) {
666
+ this.loaded.needIncoming(node, predicate);
667
+ return this.facts.find(null, DataFactory.namedNode(predicate), node).map((quad) => quad.subject);
668
+ }
669
+ /** isInstance says whether a node has a class, or a subclass of it at any depth. */
670
+ isInstance(node, classTerm) {
671
+ const types = this.outgoing(node, RDF_TYPE).map(termKey);
672
+ if (types.length === 0) return false;
673
+ const classes = this.subclasses(classTerm);
674
+ return types.some((type) => classes.has(type));
675
+ }
676
+ /** isTarget says whether a shape applies to a node by itself. */
677
+ isTarget(node, target) {
678
+ return target.nodes.has(termKey(node)) || target.classes.some((classTerm) => this.isInstance(node, classTerm)) || target.subjectsOf.some((name) => this.outgoing(node, name).length > 0) || target.objectsOf.some((name) => this.incoming(node, name).length > 0);
679
+ }
680
+ [Symbol.iterator]() {
681
+ throw new Error("A check reads only the facts it needs.");
682
+ }
683
+ find(subject, predicate, object) {
684
+ if (subject) this.loaded.needOutgoing(subject);
685
+ else if (predicate && object) this.loaded.needIncoming(object, predicate.value);
686
+ else throw new Error("A check can't look through a whole world.");
687
+ return this.facts.find(subject, predicate, object);
688
+ }
689
+ /** subclasses walks down the class tree; classes that contain each other end the walk. */
690
+ subclasses(classTerm) {
691
+ const found = /* @__PURE__ */ new Set([termKey(classTerm)]);
692
+ const pending = [classTerm];
693
+ for (const parent of pending) for (const child of this.incoming(parent, RDFS_SUBCLASS_OF)) {
694
+ if (found.has(termKey(child))) continue;
695
+ found.add(termKey(child));
696
+ pending.push(child);
697
+ }
698
+ return found;
699
+ }
700
+ };
701
+ // src/shacl/loaded-facts.ts
702
+ /**
703
+ * LoadedFacts holds the world before and after a write, as far as a check has
704
+ * looked. Run a computation over the two states with `settle`: it loads what the
705
+ * computation missed and runs it again until nothing is missing.
706
+ */
707
+ var LoadedFacts = class {
708
+ options;
709
+ before = new WorldState(this);
710
+ after = new WorldState(this);
711
+ known = /* @__PURE__ */ new Set();
712
+ deleted;
713
+ subjects = /* @__PURE__ */ new Map();
714
+ objects = /* @__PURE__ */ new Map();
715
+ loadedCount = 0;
716
+ constructor(options) {
717
+ this.options = options;
718
+ this.deleted = new Set(options.patch.deletions.map(quadKey));
719
+ for (const quad of options.patch.insertions) if (isData(quad)) this.after.add(quad);
720
+ }
721
+ /** settle runs a computation until every fact it asks for is loaded. */
722
+ async settle(compute) {
723
+ for (;;) {
724
+ const result = compute();
725
+ if (this.subjects.size === 0 && this.objects.size === 0) return result;
726
+ await this.load();
727
+ }
728
+ }
729
+ /** needOutgoing notes that a node's own facts are needed. */
730
+ needOutgoing(node) {
731
+ if (node.termType === "Literal") return;
732
+ const key = termKey(node);
733
+ if (!this.known.has(key)) this.subjects.set(key, node);
734
+ }
735
+ /** needIncoming notes that the facts pointing at a node are needed. */
736
+ needIncoming(node, predicate) {
737
+ const key = termKey(node);
738
+ if (this.known.has(`${predicate} ${key}`)) return;
739
+ const wanted = this.objects.get(predicate);
740
+ if (wanted) wanted.set(key, node);
741
+ else this.objects.set(predicate, /* @__PURE__ */ new Map([[key, node]]));
742
+ }
743
+ async load() {
744
+ const { source, predicates, limit } = this.options;
745
+ const subjects = [...this.subjects.values()];
746
+ const objects = [...this.objects];
747
+ for (const key of this.subjects.keys()) this.known.add(key);
748
+ for (const [predicate, nodes] of objects) for (const key of nodes.keys()) this.known.add(`${predicate} ${key}`);
749
+ this.subjects.clear();
750
+ this.objects.clear();
751
+ if (subjects.length > 0) this.store(await source.outgoing({
752
+ subjects,
753
+ predicates,
754
+ limit
755
+ }));
756
+ for (const [predicate, nodes] of objects) {
757
+ const request = {
758
+ objects: [...nodes.values()],
759
+ predicate,
760
+ limit
761
+ };
762
+ this.store(await source.incoming(request));
763
+ }
764
+ }
765
+ store(quads) {
766
+ this.loadedCount += quads.length;
767
+ if (this.loadedCount > this.options.limit) throw new ShaclLimitError(this.options.limit);
768
+ for (const quad of quads) {
769
+ if (!isData(quad)) continue;
770
+ this.before.add(quad);
771
+ if (!this.options.replacing && !this.deleted.has(quadKey(quad))) this.after.add(quad);
772
+ }
773
+ }
774
+ };
775
+ /** isData says whether shapes apply to a quad: the shapes themselves are not checked. */
776
+ function isData(quad) {
777
+ return quad.graph.value !== SHAPES_GRAPH;
778
+ }
779
+ /** quadKey identifies a quad, graph included: deleting one copy keeps the others. */
780
+ function quadKey(quad) {
781
+ return `${termKey(quad.graph)} ${tripleKey(quad)}`;
782
+ }
783
+ // src/shacl/shape-validator.ts
784
+ /** ShapeValidator checks single nodes against a world's shapes with `rdf-validate-shacl`. */
785
+ var ShapeValidator = class {
786
+ shapes;
787
+ validator;
788
+ constructor(shapes) {
789
+ this.shapes = shapes;
790
+ const options = {
791
+ factory: createFactory(),
792
+ maxNodeChecks: 0
793
+ };
794
+ this.validator = new SHACLValidator(shapes.index, options);
795
+ }
796
+ /** validate lists the violations of one node, in one state of the world. */
797
+ validate(focusNode, shape, state) {
798
+ const { validator } = this;
799
+ const engine = validator.validationEngine.clone();
800
+ validator.validationEngine = engine;
801
+ validator.$data = validator.factory.clownface({ dataset: state });
802
+ validator.nodeConformsToShape(focusNode, shape, engine);
803
+ return engine.getReport().results.filter((result) => result.severity?.value === `${SH}Violation`).map((result) => this.describe(result));
804
+ }
805
+ describe(result) {
806
+ const { focusNode, sourceShape, path, value } = result;
807
+ const component = result.sourceConstraintComponent?.value ?? "";
808
+ const parts = [
809
+ focusNode,
810
+ sourceShape,
811
+ path,
812
+ value
813
+ ];
814
+ const constraint = component.slice(27).replace(/ConstraintComponent$/, "");
815
+ return {
816
+ key: JSON.stringify([component, ...parts.map((term) => term && termKey(term))]),
817
+ violation: {
818
+ focusNode: label(focusNode),
819
+ ...path && { path: formatPath(expandPath(path, this.shapes)) },
820
+ ...value && { value: label(value) },
821
+ constraint,
822
+ ...sourceShape?.termType === "NamedNode" && { shape: sourceShape.value },
823
+ message: result.message[0]?.value ?? `Breaks sh:${constraint}`
824
+ }
825
+ };
826
+ }
827
+ };
828
+ function label(term) {
829
+ if (!term) return "";
830
+ return term.termType === "BlankNode" ? `_:${term.value}` : term.value;
831
+ }
832
+ /** createFactory is the validator's own factory with three parts replaced. */
833
+ function createFactory() {
834
+ const base = new SHACLValidator(new TripleIndex()).factory;
835
+ const factory = Object.create(base);
836
+ const replacements = {
837
+ [`${SH}PatternConstraintComponent`]: {
838
+ validate: createPatternCheck(),
839
+ validationMessage: "Value does not match pattern \"{$pattern}\""
840
+ },
841
+ [`${SH}ClassConstraintComponent`]: {
842
+ validate: checkClass,
843
+ validationMessage: "Value does not have class {$class}"
844
+ }
845
+ };
846
+ factory.dataset = (quads) => new TripleIndex(quads);
847
+ factory.termMap = (entries) => base.termMap([...entries ?? []].map(([term, value]) => [term, replacements[term.value] ?? value]));
848
+ return factory;
849
+ }
850
+ /** checkClass replaces a walk that never ends when two classes contain each other. */
851
+ const checkClass = (context, _focusNode, valueNode, constraint) => {
852
+ const state = context.$data.dataset;
853
+ const classTerm = constraint.getParameterValue(context.ns.sh.class);
854
+ return classTerm !== void 0 && state.isInstance(valueNode, classTerm);
855
+ };
856
+ /** createPatternCheck replaces JavaScript's pattern matching, which can hang. */
857
+ function createPatternCheck() {
858
+ const compiled = /* @__PURE__ */ new Map();
859
+ return (context, _focusNode, valueNode, constraint) => {
860
+ if (valueNode.termType === "BlankNode") return false;
861
+ const { sh } = context.ns;
862
+ const pattern = constraint.getParameterValue(sh.pattern)?.value ?? "";
863
+ const flags = constraint.getParameterValue(sh.flags)?.value ?? "";
864
+ const key = `${flags}/${pattern}`;
865
+ const matches = compiled.get(key) ?? compilePattern(pattern, flags);
866
+ compiled.set(key, matches);
867
+ return matches(valueNode.value);
868
+ };
869
+ }
870
+ // src/shacl/validate-write.ts
871
+ /** DEFAULT_MAX_CHECKED_FACTS is how many stored quads one check may read by default. */
872
+ const DEFAULT_MAX_CHECKED_FACTS = 5e4;
873
+ /**
874
+ * validateWrite rejects when a write would add new violations of the world's own
875
+ * shapes, which are the quads in {@link SHAPES_GRAPH}. Call it before writing.
876
+ *
877
+ * It checks only the nodes the write can affect, and reads only the facts those
878
+ * checks look at. A violation is new when the checked node didn't have it before, so
879
+ * shapes can be added to a world whose data breaks them. Linking another node to
880
+ * one that is broken gives the linking node a new violation.
881
+ *
882
+ * A world without shapes costs one read. A change to the class tree
883
+ * (`rdfs:subClassOf`) is treated like a change to the shapes: it applies to later
884
+ * writes and doesn't check existing nodes.
885
+ *
886
+ * @throws {ShaclViolationError} when the write adds violations.
887
+ * @throws {InvalidShapesError} when the shapes themselves can't be used.
888
+ * @throws {ShaclLimitError} when the check would read too much.
889
+ */
890
+ async function validateWrite(request) {
891
+ const { patch, source } = request;
892
+ const replacing = isReplaceImportCommit(request.context);
893
+ const shapeQuads = await shapesAfter(patch, replacing, source);
894
+ if (shapeQuads.length === 0) return;
895
+ const shapes = compileShapes(shapeQuads);
896
+ const changed = [...patch.insertions, ...patch.deletions].filter(isData);
897
+ if (changed.length === 0 || shapes.targets.length === 0) return;
898
+ const facts = new LoadedFacts({
899
+ source,
900
+ patch,
901
+ replacing,
902
+ predicates: predicatesOf(shapes.targets),
903
+ limit: request.maxCheckedFacts ?? 5e4
904
+ });
905
+ const affected = await facts.settle(() => findAffectedNodes(changed, shapes.targets, facts.after));
906
+ const validator = new ShapeValidator(shapes.graph);
907
+ const violations = await facts.settle(() => affected.flatMap(({ node, target }) => {
908
+ const now = validator.validate(node, target.shape, facts.after);
909
+ if (now.length === 0 || !facts.before.isTarget(node, target)) return now;
910
+ const old = new Set(validator.validate(node, target.shape, facts.before).map((found) => found.key));
911
+ return now.filter((found) => !old.has(found.key));
912
+ }));
913
+ if (violations.length > 0) throw new ShaclViolationError([...new Map(violations.map((found) => [found.key, found])).values()].map((found) => found.violation));
914
+ }
915
+ /** shapesAfter is the shapes graph as the write would leave it. */
916
+ async function shapesAfter(patch, replacing, source) {
917
+ const added = patch.insertions.filter((quad) => !isData(quad));
918
+ if (replacing) return added;
919
+ const removed = new Set(patch.deletions.map(quadKey));
920
+ return [...(await source.shapes()).filter((quad) => !removed.has(quadKey(quad))), ...added];
921
+ }
922
+ /**
923
+ * predicatesOf lists the properties a check may read; undefined means all of them.
924
+ * The steps that lead to a read are reads themselves, so they are in the list too.
925
+ */
926
+ function predicatesOf(targets) {
927
+ const names = /* @__PURE__ */ new Set();
928
+ for (const read of targets.flatMap((target) => target.reads)) {
929
+ if (read.predicate === void 0) return void 0;
930
+ names.add(read.predicate);
931
+ }
932
+ return [...names];
933
+ }
934
+ // src/shacl/shacl-source.ts
935
+ const { namedNode } = DataFactory;
936
+ /** createRdfjsShaclSource reads from an RDF/JS store, one pattern at a time. */
937
+ function createRdfjsShaclSource(store) {
938
+ const read = (...pattern) => collectQuadsFromStream(store.match(...pattern));
939
+ return {
940
+ shapes: () => read(null, null, null, namedNode(SHAPES_GRAPH)),
941
+ async outgoing({ subjects, predicates, limit }) {
942
+ const wanted = predicates && new Set(predicates);
943
+ const found = [];
944
+ for (const subject of subjects) {
945
+ for (const quad of await read(subject)) if (!wanted || wanted.has(quad.predicate.value)) found.push(quad);
946
+ if (found.length > limit) break;
947
+ }
948
+ return found;
949
+ },
950
+ async incoming({ objects, predicate, limit }) {
951
+ const property = namedNode(predicate);
952
+ const found = [];
953
+ for (const object of objects) {
954
+ for (const quad of await read(null, property, object)) found.push(quad);
955
+ if (found.length > limit) break;
956
+ }
957
+ return found;
958
+ }
959
+ };
960
+ }
961
+ export { DEFAULT_MAX_CHECKED_FACTS, InvalidShapesError, SHAPES_GRAPH, ShaclLimitError, ShaclViolationError, createRdfjsShaclSource, validateWrite };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wazootech/worlds-sdk",
3
- "version": "0.11.4",
3
+ "version": "0.11.5",
4
4
  "description": "Give an agent a knowledge graph it can search and query with SPARQL: in memory, on a Worlds storage package such as SQLite or Postgres, or on the hosted Worlds API.",
5
5
  "keywords": [
6
6
  "wazoo",
@@ -60,6 +60,10 @@
60
60
  "types": "./dist/rdfjs.d.ts",
61
61
  "default": "./dist/rdfjs.js"
62
62
  },
63
+ "./shacl": {
64
+ "types": "./dist/shacl.d.ts",
65
+ "default": "./dist/shacl.js"
66
+ },
63
67
  "./memory": {
64
68
  "types": "./dist/memory.d.ts",
65
69
  "default": "./dist/memory.js"
@@ -94,6 +98,7 @@
94
98
  "test": "bun test",
95
99
  "build": "tsdown",
96
100
  "check:package": "bun scripts/check-package.ts",
101
+ "mutation": "stryker run",
97
102
  "ci": "bun run fmt:check && bun run lint && bun run check && bun run test"
98
103
  },
99
104
  "dependencies": {
@@ -105,6 +110,8 @@
105
110
  "@wazootech/worlds-client": "^0.8.2",
106
111
  "ai": "^6.0.195",
107
112
  "n3": "^2.0.3",
113
+ "rdf-validate-shacl": "0.6.5",
114
+ "re2js": "2.10.0",
108
115
  "zod": "^3.25.76 || ^4.1.8"
109
116
  },
110
117
  "devDependencies": {
@@ -112,6 +119,7 @@
112
119
  "@langchain/core": "^1.1.48",
113
120
  "@langchain/textsplitters": "^1.0.1",
114
121
  "@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
122
+ "@stryker-mutator/core": "10.1.1",
115
123
  "@types/bun": "1.4.5",
116
124
  "@types/n3": "1.26.1",
117
125
  "oxlint": "1.95.0",