@ontology-kit/format 0.0.0-stage → 0.1.0-bootstrap.0
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/LICENSE +9 -0
- package/README.md +35 -2
- package/dist/edge-types.d.ts +18 -0
- package/dist/edge-types.js +26 -0
- package/dist/errors.d.ts +3 -0
- package/dist/errors.js +3 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +16 -0
- package/dist/model.d.ts +96 -0
- package/dist/model.js +501 -0
- package/dist/naming.d.ts +25 -0
- package/dist/naming.js +50 -0
- package/dist/registry.d.ts +4 -0
- package/dist/registry.js +39 -0
- package/dist/relationships.d.ts +30 -0
- package/dist/relationships.js +205 -0
- package/dist/types.d.ts +225 -0
- package/dist/types.js +13 -0
- package/package.json +49 -3
package/dist/model.js
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
1
|
+
/** Loading, saving and navigating an ontology folder (okb.json + nodes.json + edges.json). Part of @ontology-kit/format. */
|
|
2
|
+
import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname, join, resolve } from "node:path";
|
|
4
|
+
import { OkbError } from "./errors.js";
|
|
5
|
+
import { FORMAT_VERSION } from "./registry.js";
|
|
6
|
+
import * as naming from "./naming.js";
|
|
7
|
+
import { Relationships, edgeProps, isRelationship } from "./relationships.js";
|
|
8
|
+
import { DISPOSITIONS, VALUE_TYPES, } from "./types.js";
|
|
9
|
+
export { DISPOSITIONS, VALUE_TYPES };
|
|
10
|
+
export const FORMAT = FORMAT_VERSION;
|
|
11
|
+
export const MANIFEST = "okb.json";
|
|
12
|
+
const ID_PREFIX = {
|
|
13
|
+
Class: "c", Slot: "s", Instance: "i", Term: "t", ReusedOntology: "r", Source: "src", SourceLocation: "loc", Rule: "rule",
|
|
14
|
+
};
|
|
15
|
+
/** `okb show class:Genre` etc.: prefixes that say which kind of node a name refers to. */
|
|
16
|
+
const REF_PREFIX = {
|
|
17
|
+
class: "Class", slot: "Slot", instance: "Instance", term: "Term", cq: "CompetencyQuestion", question: "CompetencyQuestion", decision: "DesignDecision",
|
|
18
|
+
};
|
|
19
|
+
export { OkbError };
|
|
20
|
+
/** What a node is called: its name, or a question's/term's text, or a decision's title. */
|
|
21
|
+
export function nodeLabel(n) {
|
|
22
|
+
if ("name" in n)
|
|
23
|
+
return n.name;
|
|
24
|
+
if ("text" in n)
|
|
25
|
+
return n.text;
|
|
26
|
+
if ("title" in n)
|
|
27
|
+
return n.title;
|
|
28
|
+
return n.id;
|
|
29
|
+
}
|
|
30
|
+
/** Every name-like field a node can be looked up by. */
|
|
31
|
+
function lookupNames(n) {
|
|
32
|
+
return [("name" in n && n.name) || "", ("text" in n && n.text) || "", ("title" in n && n.title) || ""];
|
|
33
|
+
}
|
|
34
|
+
export { isRelationship };
|
|
35
|
+
export function findRoot(start) {
|
|
36
|
+
let d = resolve(start);
|
|
37
|
+
for (;;) {
|
|
38
|
+
if (existsSync(join(d, MANIFEST)))
|
|
39
|
+
return d;
|
|
40
|
+
const parent = dirname(d);
|
|
41
|
+
if (parent === d)
|
|
42
|
+
return null;
|
|
43
|
+
d = parent;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function readJson(path, fallback) {
|
|
47
|
+
return existsSync(path) ? JSON.parse(readFileSync(path, "utf8")) : fallback;
|
|
48
|
+
}
|
|
49
|
+
export class Ontology {
|
|
50
|
+
root;
|
|
51
|
+
manifest;
|
|
52
|
+
// Changed only through addNode/addEdge/remove*, which keep the indexes current.
|
|
53
|
+
_nodes;
|
|
54
|
+
_edges;
|
|
55
|
+
byId = new Map();
|
|
56
|
+
/** Relationship values and the edges that store them (see relationships.ts). */
|
|
57
|
+
rel = new Relationships(this);
|
|
58
|
+
outIdx = new Map();
|
|
59
|
+
incIdx = new Map();
|
|
60
|
+
constructor(root, manifest, nodes, edges) {
|
|
61
|
+
this.root = root;
|
|
62
|
+
this.manifest = manifest;
|
|
63
|
+
this._nodes = [...nodes];
|
|
64
|
+
this._edges = [...edges];
|
|
65
|
+
this.reindex();
|
|
66
|
+
}
|
|
67
|
+
get nodes() {
|
|
68
|
+
return this._nodes;
|
|
69
|
+
}
|
|
70
|
+
get edges() {
|
|
71
|
+
return this._edges;
|
|
72
|
+
}
|
|
73
|
+
static load(start) {
|
|
74
|
+
const root = findRoot(start);
|
|
75
|
+
if (!root) {
|
|
76
|
+
throw new OkbError(`No ontology found in ${resolve(start)} or its parents. Create one with: okb init <folder> --name "My Ontology"`);
|
|
77
|
+
}
|
|
78
|
+
// Trusted as typed; struct-well-formed reports what a hand edit got wrong.
|
|
79
|
+
const ont = new Ontology(root, readJson(join(root, MANIFEST), { format: FORMAT, currentStep: 1 }), readJson(join(root, "nodes.json"), []), readJson(join(root, "edges.json"), []));
|
|
80
|
+
if (ont.manifest.format === "okb-lpg/1")
|
|
81
|
+
ont.migrateFromV1();
|
|
82
|
+
return ont;
|
|
83
|
+
}
|
|
84
|
+
/** okb-lpg/1 stored relationship values as HAS_VALUE edges with a `slot` property. */
|
|
85
|
+
/** @internal */
|
|
86
|
+
migrateFromV1() {
|
|
87
|
+
for (const s of this.ofType("Slot")) {
|
|
88
|
+
if (s.valueType === "Instance" && !s.relType)
|
|
89
|
+
s.relType = naming.relType(s.name);
|
|
90
|
+
}
|
|
91
|
+
this.reindex();
|
|
92
|
+
const old = this.edges.filter((e) => e.type === "HAS_VALUE");
|
|
93
|
+
this._edges = this._edges.filter((e) => e.type !== "HAS_VALUE");
|
|
94
|
+
this.reindex();
|
|
95
|
+
for (const e of old)
|
|
96
|
+
if (typeof e.slot === "string")
|
|
97
|
+
this.rel.link(e.from, e.slot, e.to);
|
|
98
|
+
this.manifest.format = FORMAT;
|
|
99
|
+
}
|
|
100
|
+
static fromData(nodes, edges, manifest) {
|
|
101
|
+
return new Ontology(".", { format: FORMAT, currentStep: 8, ...manifest }, nodes, edges);
|
|
102
|
+
}
|
|
103
|
+
/** @internal */
|
|
104
|
+
save() {
|
|
105
|
+
const files = [[MANIFEST, this.manifest], ["nodes.json", this.nodes], ["edges.json", this.edges]];
|
|
106
|
+
for (const [fname, data] of files) {
|
|
107
|
+
const tmp = join(this.root, fname + ".tmp");
|
|
108
|
+
writeFileSync(tmp, JSON.stringify(data, null, 2) + "\n", "utf8");
|
|
109
|
+
renameSync(tmp, join(this.root, fname));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
// addNode/addEdge update the indexes in place; everything else that changes
|
|
113
|
+
// nodes or edges (load, removal, retyping edges) calls reindex().
|
|
114
|
+
/** Rebuild every index from scratch. The first node with a given id wins. */
|
|
115
|
+
/** @internal */
|
|
116
|
+
reindex() {
|
|
117
|
+
this.byId = new Map();
|
|
118
|
+
for (const n of this.nodes)
|
|
119
|
+
if (!this.byId.has(n.id))
|
|
120
|
+
this.byId.set(n.id, n);
|
|
121
|
+
this.outIdx = new Map();
|
|
122
|
+
this.incIdx = new Map();
|
|
123
|
+
for (const e of this.edges)
|
|
124
|
+
this.indexEdge(e);
|
|
125
|
+
}
|
|
126
|
+
indexEdge(e) {
|
|
127
|
+
const ko = `${e.from}\u0000${e.type}`;
|
|
128
|
+
const ki = `${e.to}\u0000${e.type}`;
|
|
129
|
+
let out = this.outIdx.get(ko);
|
|
130
|
+
if (!out)
|
|
131
|
+
this.outIdx.set(ko, (out = []));
|
|
132
|
+
out.push(e);
|
|
133
|
+
let inc = this.incIdx.get(ki);
|
|
134
|
+
if (!inc)
|
|
135
|
+
this.incIdx.set(ki, (inc = []));
|
|
136
|
+
inc.push(e);
|
|
137
|
+
}
|
|
138
|
+
/** The Ontology node (scope, conventions). A stand-in if the file lacks one; struct-well-formed reports that. */
|
|
139
|
+
get meta() {
|
|
140
|
+
const n = this.byId.get("ontology");
|
|
141
|
+
return n?.type === "Ontology"
|
|
142
|
+
? n
|
|
143
|
+
: { type: "Ontology", id: "ontology", name: "", domain: "", purpose: "", users: [], maintainers: [], outOfScope: [], kind: "application", reuseReviewed: false };
|
|
144
|
+
}
|
|
145
|
+
get conventions() {
|
|
146
|
+
return this.meta.conventions;
|
|
147
|
+
}
|
|
148
|
+
get step() {
|
|
149
|
+
return Number(this.manifest.currentStep ?? 1);
|
|
150
|
+
}
|
|
151
|
+
get(id) {
|
|
152
|
+
return this.byId.get(id);
|
|
153
|
+
}
|
|
154
|
+
require(id, type) {
|
|
155
|
+
const n = this.byId.get(id);
|
|
156
|
+
if (!n)
|
|
157
|
+
throw new OkbError(`'${id}' is referenced but doesn't exist. Was a file edited by hand? okb validate shows what's broken.`);
|
|
158
|
+
if (type && n.type !== type)
|
|
159
|
+
throw new OkbError(`'${id}' is ${n.type === "Instance" ? "an" : "a"} ${n.type}, not a ${type}.`);
|
|
160
|
+
return n;
|
|
161
|
+
}
|
|
162
|
+
ofType(type) {
|
|
163
|
+
return this.nodes.filter((n) => n.type === type);
|
|
164
|
+
}
|
|
165
|
+
outEdges(id, type) {
|
|
166
|
+
return this.outIdx.get(`${id}\u0000${type}`) ?? [];
|
|
167
|
+
}
|
|
168
|
+
inEdges(id, type) {
|
|
169
|
+
return this.incIdx.get(`${id}\u0000${type}`) ?? [];
|
|
170
|
+
}
|
|
171
|
+
targets(id, type) {
|
|
172
|
+
return this.outEdges(id, type).map((e) => e.to);
|
|
173
|
+
}
|
|
174
|
+
sources(id, type) {
|
|
175
|
+
return this.inEdges(id, type).map((e) => e.from);
|
|
176
|
+
}
|
|
177
|
+
edgesOf(type) {
|
|
178
|
+
return this.edges.filter((e) => e.type === type);
|
|
179
|
+
}
|
|
180
|
+
label(id) {
|
|
181
|
+
const n = this.byId.get(id);
|
|
182
|
+
return n ? nodeLabel(n) : id;
|
|
183
|
+
}
|
|
184
|
+
find(ref, types, required = true) {
|
|
185
|
+
let ts = typeof types === "string" ? [types] : types;
|
|
186
|
+
const prefixed = ref.match(/^(class|slot|instance|term|cq|question|decision):(.+)$/i);
|
|
187
|
+
if (prefixed) {
|
|
188
|
+
ts = [REF_PREFIX[prefixed[1].toLowerCase()]];
|
|
189
|
+
ref = prefixed[2].trim();
|
|
190
|
+
}
|
|
191
|
+
const ok = (n) => !ts || ts.includes(n.type);
|
|
192
|
+
const direct = this.byId.get(ref);
|
|
193
|
+
if (direct && ok(direct))
|
|
194
|
+
return direct;
|
|
195
|
+
const k = naming.key(ref);
|
|
196
|
+
let hits = this.nodes.filter((n) => ok(n) && k && lookupNames(n).some((x) => naming.key(x) === k));
|
|
197
|
+
if (hits.length === 0 && /^\d+$/.test(ref) && ts) {
|
|
198
|
+
if (ts.includes("CompetencyQuestion"))
|
|
199
|
+
hits = this.nodes.filter((n) => n.id === `cq.${ref}`);
|
|
200
|
+
if (ts.includes("DesignDecision"))
|
|
201
|
+
hits = hits.concat(this.nodes.filter((n) => n.id === `d.${ref}`));
|
|
202
|
+
}
|
|
203
|
+
if (hits.length > 1 && !ts) {
|
|
204
|
+
// Untyped lookups prefer the modeling elements over brainstorm terms, questions, etc.
|
|
205
|
+
for (const pref of ["Class", "Slot", "Instance"]) {
|
|
206
|
+
const h = hits.filter((n) => n.type === pref);
|
|
207
|
+
if (h.length === 1)
|
|
208
|
+
return h[0];
|
|
209
|
+
if (h.length > 1)
|
|
210
|
+
break;
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
if (hits.length === 1)
|
|
214
|
+
return hits[0];
|
|
215
|
+
if (hits.length > 1) {
|
|
216
|
+
const hint = hits.map((h) => `${h.type.toLowerCase()}:${nameOrText(h) ?? h.id}`).join(" or ");
|
|
217
|
+
throw new OkbError(`'${ref}' matches more than one thing (${hits.map((h) => `${h.type} ${nameOrText(h)}`).join(", ")}). Say which one: ${hint}`);
|
|
218
|
+
}
|
|
219
|
+
if (!required)
|
|
220
|
+
return undefined;
|
|
221
|
+
const what = ts ? ts.join(" or ") : "node";
|
|
222
|
+
if (ts) {
|
|
223
|
+
const wanted = ts;
|
|
224
|
+
const other = this.nodes.find((n) => !wanted.includes(n.type) && k && lookupNames(n).slice(0, 2).some((x) => naming.key(x) === k));
|
|
225
|
+
if (other) {
|
|
226
|
+
const extra = other.type === "Instance" && ts.includes("Class")
|
|
227
|
+
? " Instances can't have subclasses or be used as a class (rule inst-are-leaves); if you need that, make it a class."
|
|
228
|
+
: "";
|
|
229
|
+
throw new OkbError(`'${ref}' is ${naming.an(other.type)}, not ${naming.an(what)}.${extra}`);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
const sugg = this.suggest(ref, ts);
|
|
233
|
+
throw new OkbError(`No ${what} named '${ref}'.${sugg.length ? ` Did you mean: ${sugg.join(", ")}?` : ""}`);
|
|
234
|
+
}
|
|
235
|
+
/** @internal */
|
|
236
|
+
suggest(ref, types, limit = 3) {
|
|
237
|
+
const k = naming.key(ref);
|
|
238
|
+
const scored = this.nodes
|
|
239
|
+
.flatMap((n) => ("name" in n && n.name && (!types || types.includes(n.type)) ? [n.name] : []))
|
|
240
|
+
.map((name) => ({ name, d: editDistance(k, naming.key(name)) }))
|
|
241
|
+
.filter((x) => x.d <= Math.max(2, Math.floor(k.length / 3)))
|
|
242
|
+
.sort((a, b) => a.d - b.d);
|
|
243
|
+
return scored.slice(0, limit).map((x) => x.name);
|
|
244
|
+
}
|
|
245
|
+
/** @internal */
|
|
246
|
+
newId(type, name) {
|
|
247
|
+
if (type === "CompetencyQuestion" || type === "DesignDecision") {
|
|
248
|
+
const p = type === "CompetencyQuestion" ? "cq" : "d";
|
|
249
|
+
let i = 1;
|
|
250
|
+
while (this.byId.has(`${p}.${i}`))
|
|
251
|
+
i++;
|
|
252
|
+
return `${p}.${i}`;
|
|
253
|
+
}
|
|
254
|
+
const base = `${ID_PREFIX[type] ?? type.toLowerCase()}.${naming.slug(name ?? type)}`;
|
|
255
|
+
let id = base;
|
|
256
|
+
for (let i = 2; this.byId.has(id); i++)
|
|
257
|
+
id = `${base}-${i}`;
|
|
258
|
+
return id;
|
|
259
|
+
}
|
|
260
|
+
/** @internal */
|
|
261
|
+
addNode(node) {
|
|
262
|
+
if (this.byId.has(node.id))
|
|
263
|
+
throw new OkbError(`A node with id ${node.id} already exists.`);
|
|
264
|
+
this._nodes.push(node);
|
|
265
|
+
this.byId.set(node.id, node);
|
|
266
|
+
return node;
|
|
267
|
+
}
|
|
268
|
+
/** @internal */
|
|
269
|
+
addEdge(from, type, to, props = {}) {
|
|
270
|
+
const existing = this.outEdges(from, type).find((e) => e.to === to && Object.entries(props).every(([k, v]) => e[k] === v));
|
|
271
|
+
if (existing)
|
|
272
|
+
return existing;
|
|
273
|
+
const e = { from, type, to, ...props };
|
|
274
|
+
this._edges.push(e);
|
|
275
|
+
this.indexEdge(e);
|
|
276
|
+
return e;
|
|
277
|
+
}
|
|
278
|
+
/** @internal */
|
|
279
|
+
removeEdges(pred) {
|
|
280
|
+
const before = this.edges.length;
|
|
281
|
+
this._edges = this._edges.filter((e) => !pred(e));
|
|
282
|
+
this.reindex();
|
|
283
|
+
return before - this.edges.length;
|
|
284
|
+
}
|
|
285
|
+
/** Change every edge of one type to another (a relationship's edge type was renamed). */
|
|
286
|
+
/** @internal */
|
|
287
|
+
retypeEdges(from, to) {
|
|
288
|
+
for (const e of this._edges)
|
|
289
|
+
if (e.type === from)
|
|
290
|
+
e.type = to;
|
|
291
|
+
this.reindex();
|
|
292
|
+
}
|
|
293
|
+
/** Remove a node, every edge touching it, and every value stored under its id. For a relationship slot, call rel.drop() first. */
|
|
294
|
+
/** @internal */
|
|
295
|
+
removeNode(id) {
|
|
296
|
+
this._nodes = this._nodes.filter((x) => x.id !== id);
|
|
297
|
+
this._edges = this._edges.filter((e) => e.from !== id && e.to !== id);
|
|
298
|
+
for (const x of this.nodes) {
|
|
299
|
+
if (x.type === "Instance" || x.type === "Rule")
|
|
300
|
+
delete x.values?.[id];
|
|
301
|
+
else if (x.type === "Class") {
|
|
302
|
+
delete x.fixedValues?.[id];
|
|
303
|
+
delete x.defaults?.[id];
|
|
304
|
+
delete x.facetOverrides?.[id];
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
this.reindex();
|
|
308
|
+
}
|
|
309
|
+
parents(id) {
|
|
310
|
+
return this.targets(id, "IS_A");
|
|
311
|
+
}
|
|
312
|
+
children(id) {
|
|
313
|
+
return this.sources(id, "IS_A");
|
|
314
|
+
}
|
|
315
|
+
/** All classes above id (not including id). Cycle-safe. */
|
|
316
|
+
ancestors(id) {
|
|
317
|
+
return this.walk(id, (x) => this.parents(x));
|
|
318
|
+
}
|
|
319
|
+
descendants(id) {
|
|
320
|
+
return this.walk(id, (x) => this.children(x));
|
|
321
|
+
}
|
|
322
|
+
walk(id, next) {
|
|
323
|
+
const seen = new Set();
|
|
324
|
+
const stack = [...next(id)];
|
|
325
|
+
for (let c = stack.pop(); c !== undefined; c = stack.pop()) {
|
|
326
|
+
if (seen.has(c) || c === id)
|
|
327
|
+
continue;
|
|
328
|
+
seen.add(c);
|
|
329
|
+
stack.push(...next(c));
|
|
330
|
+
}
|
|
331
|
+
return seen;
|
|
332
|
+
}
|
|
333
|
+
/** id plus all its ancestors. */
|
|
334
|
+
up(id) {
|
|
335
|
+
return new Set([id, ...this.ancestors(id)]);
|
|
336
|
+
}
|
|
337
|
+
/** a is b, or a (transitively) IS_A b. */
|
|
338
|
+
isSub(a, b) {
|
|
339
|
+
return a === b || this.ancestors(a).has(b);
|
|
340
|
+
}
|
|
341
|
+
/** a and b can never share members: a declared DISJOINT_WITH pair covers them (directly or via ancestors). */
|
|
342
|
+
disjointImplied(a, b) {
|
|
343
|
+
const ua = this.up(a);
|
|
344
|
+
const ub = this.up(b);
|
|
345
|
+
return this.edgesOf("DISJOINT_WITH").some((e) => (ua.has(e.from) && ub.has(e.to)) || (ua.has(e.to) && ub.has(e.from)));
|
|
346
|
+
}
|
|
347
|
+
roots() {
|
|
348
|
+
return this.ofType("Class").filter((c) => this.parents(c.id).length === 0).map((c) => c.id);
|
|
349
|
+
}
|
|
350
|
+
/** Every class an instance belongs to, including inherited ones. */
|
|
351
|
+
instanceClasses(id) {
|
|
352
|
+
const out = new Set();
|
|
353
|
+
for (const c of this.targets(id, "INSTANCE_OF"))
|
|
354
|
+
for (const x of this.up(c))
|
|
355
|
+
out.add(x);
|
|
356
|
+
return out;
|
|
357
|
+
}
|
|
358
|
+
/** Classes a node belongs to for slot purposes: an instance's classes, or a class and its ancestors. */
|
|
359
|
+
classContext(id) {
|
|
360
|
+
const n = this.byId.get(id);
|
|
361
|
+
if (n?.type === "Rule")
|
|
362
|
+
return [];
|
|
363
|
+
return [...(n?.type === "Instance" ? this.instanceClasses(id) : this.up(id))];
|
|
364
|
+
}
|
|
365
|
+
/** Whether following `type` edges from `from` ever reaches `to`. */
|
|
366
|
+
reaches(from, to, type) {
|
|
367
|
+
const seen = new Set();
|
|
368
|
+
const stack = [from];
|
|
369
|
+
for (let id = stack.pop(); id !== undefined; id = stack.pop()) {
|
|
370
|
+
if (id === to)
|
|
371
|
+
return true;
|
|
372
|
+
if (seen.has(id))
|
|
373
|
+
continue;
|
|
374
|
+
seen.add(id);
|
|
375
|
+
stack.push(...this.targets(id, type));
|
|
376
|
+
}
|
|
377
|
+
return false;
|
|
378
|
+
}
|
|
379
|
+
ownSlots(id) {
|
|
380
|
+
return this.targets(id, "HAS_SLOT");
|
|
381
|
+
}
|
|
382
|
+
slotsOfClasses(classes) {
|
|
383
|
+
const out = [];
|
|
384
|
+
for (const c of classes)
|
|
385
|
+
for (const s of this.ownSlots(c))
|
|
386
|
+
if (!out.includes(s))
|
|
387
|
+
out.push(s);
|
|
388
|
+
return out;
|
|
389
|
+
}
|
|
390
|
+
/** Own + inherited slots of a class, all slots of an instance, or the slots declared to apply to Rules. */
|
|
391
|
+
applicableSlots(id) {
|
|
392
|
+
const n = this.byId.get(id);
|
|
393
|
+
if (n?.type === "Instance")
|
|
394
|
+
return this.slotsOfClasses(this.instanceClasses(id));
|
|
395
|
+
if (n?.type === "Rule")
|
|
396
|
+
return this.ofType("Slot").filter((s) => s.appliesToRules).map((s) => s.id);
|
|
397
|
+
return this.slotsOfClasses([id, ...this.ancestors(id)]);
|
|
398
|
+
}
|
|
399
|
+
domain(slotId) {
|
|
400
|
+
return this.sources(slotId, "HAS_SLOT");
|
|
401
|
+
}
|
|
402
|
+
/** Whether a slot belongs to anything: a class, or every Rule. */
|
|
403
|
+
isAttached(slotId) {
|
|
404
|
+
const s = this.byId.get(slotId);
|
|
405
|
+
return this.domain(slotId).length > 0 || (s?.type === "Slot" && s.appliesToRules === true);
|
|
406
|
+
}
|
|
407
|
+
range(slotId) {
|
|
408
|
+
return this.targets(slotId, "RANGE");
|
|
409
|
+
}
|
|
410
|
+
inverses(slotId) {
|
|
411
|
+
return [...this.targets(slotId, "INVERSE_OF"), ...this.sources(slotId, "INVERSE_OF")];
|
|
412
|
+
}
|
|
413
|
+
/** Slot facets with overrides from any of `classes` applied (most restrictive wins). */
|
|
414
|
+
effectiveFacets(slotId, classes) {
|
|
415
|
+
// A HAS_SLOT edge to something that isn't a slot (a hand edit) gets no facets; struct-well-formed reports it.
|
|
416
|
+
const n = this.byId.get(slotId);
|
|
417
|
+
const s = n?.type === "Slot" ? n : {};
|
|
418
|
+
const single = s.cardinality === "single";
|
|
419
|
+
let max = s.maxCardinality ?? (single ? 1 : null);
|
|
420
|
+
if (single && max !== null)
|
|
421
|
+
max = Math.min(max, 1);
|
|
422
|
+
const f = {
|
|
423
|
+
valueType: s.valueType,
|
|
424
|
+
allowedValues: Array.isArray(s.allowedValues) ? [...s.allowedValues] : null,
|
|
425
|
+
min: s.minCardinality ?? 0,
|
|
426
|
+
max,
|
|
427
|
+
range: this.range(slotId),
|
|
428
|
+
overriddenBy: [],
|
|
429
|
+
};
|
|
430
|
+
for (const c of classes) {
|
|
431
|
+
const cn = this.byId.get(c);
|
|
432
|
+
const ov = cn?.type === "Class" ? cn.facetOverrides?.[slotId] : undefined;
|
|
433
|
+
if (!ov)
|
|
434
|
+
continue;
|
|
435
|
+
f.overriddenBy.push(c);
|
|
436
|
+
const allowed = ov.allowedValues;
|
|
437
|
+
if (Array.isArray(allowed)) {
|
|
438
|
+
const base = f.allowedValues ?? allowed;
|
|
439
|
+
f.allowedValues = base.filter((v) => allowed.includes(v));
|
|
440
|
+
}
|
|
441
|
+
if (typeof ov.minCardinality === "number")
|
|
442
|
+
f.min = Math.max(f.min, ov.minCardinality);
|
|
443
|
+
if (typeof ov.maxCardinality === "number")
|
|
444
|
+
f.max = f.max === null ? ov.maxCardinality : Math.min(f.max, ov.maxCardinality);
|
|
445
|
+
if (Array.isArray(ov.range) && ov.range.length)
|
|
446
|
+
f.range = [...ov.range];
|
|
447
|
+
}
|
|
448
|
+
return f;
|
|
449
|
+
}
|
|
450
|
+
/** Values a node states for a slot: literals (values / fixedValues) plus relationship targets. */
|
|
451
|
+
statedValues(id, slotId) {
|
|
452
|
+
const n = this.byId.get(id);
|
|
453
|
+
if (!n)
|
|
454
|
+
return [];
|
|
455
|
+
const out = [];
|
|
456
|
+
const lit = literalValue(n, slotId);
|
|
457
|
+
if (lit !== undefined)
|
|
458
|
+
out.push(...(Array.isArray(lit) ? lit : [lit]));
|
|
459
|
+
out.push(...this.rel.values(id, slotId));
|
|
460
|
+
return out;
|
|
461
|
+
}
|
|
462
|
+
/** The fixed (class-level) values for a slot inherited from any of `classes`, with the class that set them. */
|
|
463
|
+
inheritedFixed(slotId, classes, exclude) {
|
|
464
|
+
for (const c of classes) {
|
|
465
|
+
if (c === exclude)
|
|
466
|
+
continue;
|
|
467
|
+
const vals = this.statedValues(c, slotId);
|
|
468
|
+
if (vals.length)
|
|
469
|
+
return { cls: c, values: vals };
|
|
470
|
+
}
|
|
471
|
+
return null;
|
|
472
|
+
}
|
|
473
|
+
}
|
|
474
|
+
/** A node's own literal value for a slot: an instance's value, or a class's fixed value. */
|
|
475
|
+
export function literalValue(n, slotId) {
|
|
476
|
+
if (n.type === "Instance" || n.type === "Rule")
|
|
477
|
+
return n.values?.[slotId];
|
|
478
|
+
if (n.type === "Class")
|
|
479
|
+
return n.fixedValues?.[slotId];
|
|
480
|
+
return undefined;
|
|
481
|
+
}
|
|
482
|
+
/** Where a node keeps its own literal values: instances and rules in `values`, classes in `fixedValues`. */
|
|
483
|
+
export function literalValues(n) {
|
|
484
|
+
return n.type === "Class" ? (n.fixedValues ??= {}) : (n.values ??= {});
|
|
485
|
+
}
|
|
486
|
+
/** A node's name, or a question's/term's text (undefined for anything else). */
|
|
487
|
+
export function nameOrText(n) {
|
|
488
|
+
return "name" in n ? n.name : "text" in n ? n.text : undefined;
|
|
489
|
+
}
|
|
490
|
+
export { edgeProps };
|
|
491
|
+
export function editDistance(a, b) {
|
|
492
|
+
const dp = Array.from({ length: a.length + 1 }, (_, i) => [i, ...Array(b.length).fill(0)]);
|
|
493
|
+
for (let j = 1; j <= b.length; j++)
|
|
494
|
+
dp[0][j] = j;
|
|
495
|
+
for (let i = 1; i <= a.length; i++) {
|
|
496
|
+
for (let j = 1; j <= b.length; j++) {
|
|
497
|
+
dp[i][j] = Math.min(dp[i - 1][j] + 1, dp[i][j - 1] + 1, dp[i - 1][j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
return dp[a.length][b.length];
|
|
501
|
+
}
|
package/dist/naming.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How names turn into identities: the folding that makes lookups case- and delimiter-insensitive,
|
|
3
|
+
* the slug an id is built from, and the edge type a relationship slot's name becomes. These are the
|
|
4
|
+
* parts of naming the file format itself depends on. okb keeps the style rules (PascalCase, plurals).
|
|
5
|
+
*/
|
|
6
|
+
/** 'Rosé' -> 'Rose': decompose, then drop the combining marks. */
|
|
7
|
+
export declare function stripAccents(s: string): string;
|
|
8
|
+
/** 'RedWine' / 'red_wine' / 'Red wine' -> ['red', 'wine'] */
|
|
9
|
+
export declare function tokens(name: string): string[];
|
|
10
|
+
/** Words with original capitalization (and trailing dots kept, for abbreviation checks). */
|
|
11
|
+
export declare function rawTokens(name: string): string[];
|
|
12
|
+
/** Lowercase letters and digits only, without accents: 'Rosé Wine!' -> 'rosewine'. */
|
|
13
|
+
export declare function fold(text: string): string;
|
|
14
|
+
/**
|
|
15
|
+
* Case- and delimiter-insensitive identity for uniqueness checks (the fold of a
|
|
16
|
+
* name). Memoized: name lookups compare against every node's name, so the same
|
|
17
|
+
* short strings recur constantly.
|
|
18
|
+
*/
|
|
19
|
+
export declare function key(name: string): string;
|
|
20
|
+
/** The part of an id built from a name: 'Red Wine' -> 'red-wine'. */
|
|
21
|
+
export declare function slug(name: string): string;
|
|
22
|
+
/** "a Winery" / "an Author" */
|
|
23
|
+
export declare const an: (w: string) => string;
|
|
24
|
+
/** Relationship (edge) type for a slot name: 'goesWellWith' -> 'GOES_WELL_WITH' (the openCypher convention). */
|
|
25
|
+
export declare function relType(slotName: string): string;
|
package/dist/naming.js
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How names turn into identities: the folding that makes lookups case- and delimiter-insensitive,
|
|
3
|
+
* the slug an id is built from, and the edge type a relationship slot's name becomes. These are the
|
|
4
|
+
* parts of naming the file format itself depends on. okb keeps the style rules (PascalCase, plurals).
|
|
5
|
+
*/
|
|
6
|
+
/** 'Rosé' -> 'Rose': decompose, then drop the combining marks. */
|
|
7
|
+
export function stripAccents(s) {
|
|
8
|
+
return s.normalize("NFKD").replace(/\p{M}/gu, "");
|
|
9
|
+
}
|
|
10
|
+
function splitWords(name, keepDots = false) {
|
|
11
|
+
const s = name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2");
|
|
12
|
+
return s.split(keepDots ? /[^A-Za-z0-9.]+/ : /[^A-Za-z0-9]+/).filter(Boolean);
|
|
13
|
+
}
|
|
14
|
+
/** 'RedWine' / 'red_wine' / 'Red wine' -> ['red', 'wine'] */
|
|
15
|
+
export function tokens(name) {
|
|
16
|
+
return splitWords(name).map((t) => t.toLowerCase());
|
|
17
|
+
}
|
|
18
|
+
/** Words with original capitalization (and trailing dots kept, for abbreviation checks). */
|
|
19
|
+
export function rawTokens(name) {
|
|
20
|
+
return splitWords(name, true);
|
|
21
|
+
}
|
|
22
|
+
/** Lowercase letters and digits only, without accents: 'Rosé Wine!' -> 'rosewine'. */
|
|
23
|
+
export function fold(text) {
|
|
24
|
+
return stripAccents(text).toLowerCase().replace(/[^a-z0-9]/g, "");
|
|
25
|
+
}
|
|
26
|
+
const keyCache = new Map();
|
|
27
|
+
/**
|
|
28
|
+
* Case- and delimiter-insensitive identity for uniqueness checks (the fold of a
|
|
29
|
+
* name). Memoized: name lookups compare against every node's name, so the same
|
|
30
|
+
* short strings recur constantly.
|
|
31
|
+
*/
|
|
32
|
+
export function key(name) {
|
|
33
|
+
let k = keyCache.get(name);
|
|
34
|
+
if (k === undefined) {
|
|
35
|
+
k = fold(name);
|
|
36
|
+
keyCache.set(name, k);
|
|
37
|
+
}
|
|
38
|
+
return k;
|
|
39
|
+
}
|
|
40
|
+
/** The part of an id built from a name: 'Red Wine' -> 'red-wine'. */
|
|
41
|
+
export function slug(name) {
|
|
42
|
+
const ts = tokens(stripAccents(name));
|
|
43
|
+
return ts.length ? ts.join("-") : "x";
|
|
44
|
+
}
|
|
45
|
+
/** "a Winery" / "an Author" */
|
|
46
|
+
export const an = (w) => (/^[aeiou]/i.test(w) ? "an " : "a ") + w;
|
|
47
|
+
/** Relationship (edge) type for a slot name: 'goesWellWith' -> 'GOES_WELL_WITH' (the openCypher convention). */
|
|
48
|
+
export function relType(slotName) {
|
|
49
|
+
return tokens(stripAccents(slotName)).join("_").toUpperCase();
|
|
50
|
+
}
|
package/dist/registry.js
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Generated by packages/okb/meta-kb/build.ts (pnpm build:meta) from packages/okb/meta-kb/src/format.yaml.
|
|
2
|
+
// Don't edit by hand: change the YAML and rebuild. A test checks this file against the compiled meta-KB.
|
|
3
|
+
export const FORMAT_VERSION = "okb-lpg/2";
|
|
4
|
+
export const NODE_TYPE_NAMES = [
|
|
5
|
+
"Ontology",
|
|
6
|
+
"CompetencyQuestion",
|
|
7
|
+
"Term",
|
|
8
|
+
"ReusedOntology",
|
|
9
|
+
"Class",
|
|
10
|
+
"Slot",
|
|
11
|
+
"Instance",
|
|
12
|
+
"DesignDecision",
|
|
13
|
+
"Source",
|
|
14
|
+
"SourceLocation",
|
|
15
|
+
"Rule",
|
|
16
|
+
];
|
|
17
|
+
export const EDGE_TYPE_NAMES = [
|
|
18
|
+
"IS_A",
|
|
19
|
+
"INSTANCE_OF",
|
|
20
|
+
"HAS_SLOT",
|
|
21
|
+
"RANGE",
|
|
22
|
+
"INVERSE_OF",
|
|
23
|
+
"DISJOINT_WITH",
|
|
24
|
+
"NEEDS",
|
|
25
|
+
"BECAME",
|
|
26
|
+
"ABOUT",
|
|
27
|
+
"CITES",
|
|
28
|
+
"PART_OF",
|
|
29
|
+
"GOVERNS",
|
|
30
|
+
"REFINES",
|
|
31
|
+
"FULFILLS",
|
|
32
|
+
];
|
|
33
|
+
export const PROVENANCE_EDGE_TYPE_NAMES = [
|
|
34
|
+
"CITES",
|
|
35
|
+
"PART_OF",
|
|
36
|
+
"GOVERNS",
|
|
37
|
+
"REFINES",
|
|
38
|
+
"FULFILLS",
|
|
39
|
+
];
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Ontology } from "./model.js";
|
|
2
|
+
import type { EdgePropertyDecl, GraphEdge, RelationshipSlot } from "./types.js";
|
|
3
|
+
/** How one slot's values are stored: the edge type, and whether this slot reads it backwards. */
|
|
4
|
+
export interface LinkSpec {
|
|
5
|
+
type: string;
|
|
6
|
+
reverse: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** An edge's own properties (everything except from/type/to). */
|
|
9
|
+
export declare function edgeProps(e: GraphEdge): Record<string, unknown>;
|
|
10
|
+
export declare class Relationships {
|
|
11
|
+
private readonly ont;
|
|
12
|
+
constructor(ont: Ontology);
|
|
13
|
+
/** The slot that stores a relationship's edges: the slot itself, or the one it's the inverse of. */
|
|
14
|
+
primary(slotId: string): string;
|
|
15
|
+
isPrimary(slotId: string): boolean;
|
|
16
|
+
spec(slotId: string): LinkSpec | null;
|
|
17
|
+
/** Edge types that hold relationship values, mapped to the slot that stores each. */
|
|
18
|
+
edgeTypes(): Map<string, string>;
|
|
19
|
+
/** The nodes `id` is linked to through a relationship slot (either direction). */
|
|
20
|
+
values(id: string, slotId: string): string[];
|
|
21
|
+
/** The stored edge behind one relationship value, whichever end it's read from. */
|
|
22
|
+
edge(id: string, slotId: string, target: string): GraphEdge | undefined;
|
|
23
|
+
/** Relationship slots `id` has any values for (either direction). */
|
|
24
|
+
slotsWithValues(id: string): string[];
|
|
25
|
+
/** The edge properties a relationship's edges can carry (declared on its primary slot). */
|
|
26
|
+
edgeProperties(slotId: string): EdgePropertyDecl[];
|
|
27
|
+
}
|
|
28
|
+
export declare function isRelationship(s: {
|
|
29
|
+
type: string;
|
|
30
|
+
} | undefined): s is RelationshipSlot;
|