@ontology-kit/reader 0.3.0-alpha.210 → 0.3.0-alpha.66

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/dist/index.d.ts CHANGED
@@ -12,6 +12,8 @@ export { Ontology, FORMAT, MANIFEST, findRoot, nodeLabel, nameOrText, literalVal
12
12
  export { OkbError } from "./errors.js";
13
13
  export { Relationships, isRelationship, edgeProps } from "./relationships.js";
14
14
  export type { LinkSpec } from "./relationships.js";
15
+ export { MAX_DEPTH, checkQuery, query, queryFind, queryGet, querySlots, queryTraverse, resultNames } from "./query.js";
16
+ export type { FindQuery, GetResult, NodeHit, Query, QueryResult, QueryValue, SlotHit, SlotsQuery, TraverseHit, TraverseQuery, } from "./query.js";
15
17
  export { NODE_TYPES, STRUCTURAL_EDGE_TYPES, PROVENANCE_EDGE_TYPES, isStructuralEdgeType, isProvenanceEdgeType } from "./edge-types.js";
16
18
  export { fold, key, rawTokens, relType, slug, stripAccents, tokens } from "./naming.js";
17
19
  export { CARDINALITIES, DISPOSITIONS, MODALITIES, VALUE_TYPES, VERIFICATION_STATUSES, } from "./types.js";
package/dist/index.js CHANGED
@@ -11,6 +11,7 @@
11
11
  export { Ontology, FORMAT, MANIFEST, findRoot, nodeLabel, nameOrText, literalValue, literalValues } from "./model.js";
12
12
  export { OkbError } from "./errors.js";
13
13
  export { Relationships, isRelationship, edgeProps } from "./relationships.js";
14
+ export { MAX_DEPTH, checkQuery, query, queryFind, queryGet, querySlots, queryTraverse, resultNames } from "./query.js";
14
15
  export { NODE_TYPES, STRUCTURAL_EDGE_TYPES, PROVENANCE_EDGE_TYPES, isStructuralEdgeType, isProvenanceEdgeType } from "./edge-types.js";
15
16
  export { fold, key, rawTokens, relType, slug, stripAccents, tokens } from "./naming.js";
16
17
  export { CARDINALITIES, DISPOSITIONS, MODALITIES, VALUE_TYPES, VERIFICATION_STATUSES, } from "./types.js";
package/dist/layout.d.ts CHANGED
@@ -1,6 +1,19 @@
1
1
  import type { GraphEdge, OkbNode } from "./types.js";
2
2
  export declare const NODES_FILE = "nodes.jsonl";
3
3
  export declare const EDGES_FILE = "edges.jsonl";
4
+ /**
5
+ * The marker of a save in progress (decision 0033). It is written once all three temp files are complete and removed once
6
+ * the last rename is done, so a marker on disk means "finish this save": `finishSave` renames what is left.
7
+ * `*.tmp` is git-ignored by `okb init`, so the marker is too.
8
+ */
9
+ export declare const SAVING_MARKER = ".okb.saving.tmp";
10
+ /**
11
+ * Test seam (internal: not exported from the package index). `at` is called after each step of a save or a roll-forward
12
+ * (`temps`, `marker`, `renamed:<file>`, `legacy`, `unmarked`); a test throws from it to stop where a crash would.
13
+ */
14
+ export declare const saveSeam: {
15
+ at: (_step: string) => void;
16
+ };
4
17
  /** Compare ids so `cq.2` sorts before `cq.10` and the order is the same on every machine. */
5
18
  export declare function compareNatural(a: string, b: string): number;
6
19
  export declare function nodeLine(n: OkbNode): string;
@@ -14,5 +27,18 @@ export declare function readGraph(root: string): {
14
27
  nodes: OkbNode[];
15
28
  edges: GraphEdge[];
16
29
  };
17
- /** Write the three files (each atomically, all temp files first) and remove the old-layout files. */
30
+ /**
31
+ * Write the three files so that a crash at any point leaves either the old files or a save the next load finishes:
32
+ * all temp files first (flushed), then the marker, then the renames with `okb.json` last, then the old-layout files
33
+ * and the marker are removed. The caller holds the folder's lock (a new folder has no other writer).
34
+ */
18
35
  export declare function writeGraph(root: string, manifest: unknown, nodes: readonly OkbNode[], edges: readonly GraphEdge[]): void;
36
+ /** Whether a save was interrupted after its marker was written (a save in flight looks the same; check the lock). */
37
+ export declare function saveInterrupted(root: string): boolean;
38
+ /**
39
+ * Finish an interrupted save: a marker means all three temp files were complete, so renaming the ones that are left gives
40
+ * exactly the folder the save would have made. Safe to run again after a crash of its own. The caller holds the lock.
41
+ * The renames go in a fixed order, so the temp files that remain must be a tail of it; anything else (a temp file
42
+ * deleted by hand, say) is not a state a crash makes, and it stops with an error instead of guessing.
43
+ */
44
+ export declare function finishSave(root: string): void;
package/dist/layout.js CHANGED
@@ -4,13 +4,27 @@
4
4
  * touch different lines and `git merge` has nothing to conflict on. Older folders (`nodes.json` and
5
5
  * `edges.json`, each one JSON array) still load. Part of @ontology-kit/reader.
6
6
  */
7
- import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
7
+ import { closeSync, existsSync, fsyncSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import { OkbError } from "./errors.js";
10
10
  export const NODES_FILE = "nodes.jsonl";
11
11
  export const EDGES_FILE = "edges.jsonl";
12
12
  const LEGACY_NODES = "nodes.json";
13
13
  const LEGACY_EDGES = "edges.json";
14
+ const MANIFEST_FILE = "okb.json";
15
+ /**
16
+ * The marker of a save in progress (decision 0033). It is written once all three temp files are complete and removed once
17
+ * the last rename is done, so a marker on disk means "finish this save": `finishSave` renames what is left.
18
+ * `*.tmp` is git-ignored by `okb init`, so the marker is too.
19
+ */
20
+ export const SAVING_MARKER = ".okb.saving.tmp";
21
+ /** The rename order. `okb.json` is last: a crash then leaves an old `format` over new data, which loads fine. */
22
+ const SAVE_ORDER = [NODES_FILE, EDGES_FILE, MANIFEST_FILE];
23
+ /**
24
+ * Test seam (internal: not exported from the package index). `at` is called after each step of a save or a roll-forward
25
+ * (`temps`, `marker`, `renamed:<file>`, `legacy`, `unmarked`); a test throws from it to stop where a crash would.
26
+ */
27
+ export const saveSeam = { at: (_step) => { } };
14
28
  /** Compare ids so `cq.2` sorts before `cq.10` and the order is the same on every machine. */
15
29
  export function compareNatural(a, b) {
16
30
  const pa = a.split(/(\d+)/);
@@ -88,7 +102,10 @@ export function readGraph(root) {
88
102
  const a = join(root, jsonl);
89
103
  const b = join(root, legacy);
90
104
  if (existsSync(a) && existsSync(b)) {
91
- throw new OkbError(`Both ${jsonl} and ${legacy} exist. ${jsonl} is the current layout; if ${legacy} is left over from a merge, check it has nothing you need, then delete it.`);
105
+ throw new OkbError(`Both ${jsonl} and ${legacy} exist. ${jsonl} is the current layout, but don't just delete ${legacy}: an interrupted save or migration ` +
106
+ `(by an okb older than 0.3.0) can leave some files new and some old, and deleting the old file then keeps new nodes with old edges. ` +
107
+ `Restore the folder from git or a backup, or, if nodes.jsonl.tmp, edges.jsonl.tmp or okb.json.tmp are there, rename each over ` +
108
+ `the file it names (drop the .tmp) and then delete ${LEGACY_NODES} and ${LEGACY_EDGES}. If ${legacy} is only left over from a merge, check it has nothing you need, then delete it.`);
92
109
  }
93
110
  if (existsSync(a))
94
111
  return parseLines(readFileSync(a, "utf8"), jsonl);
@@ -98,19 +115,97 @@ export function readGraph(root) {
98
115
  };
99
116
  return { nodes: side(NODES_FILE, LEGACY_NODES), edges: side(EDGES_FILE, LEGACY_EDGES) };
100
117
  }
101
- /** Write the three files (each atomically, all temp files first) and remove the old-layout files. */
118
+ /** Flush a file's data to disk. A directory can't be opened for this on Windows; there the call does nothing. */
119
+ function flush(path) {
120
+ let fd;
121
+ try {
122
+ fd = openSync(path, "r");
123
+ }
124
+ catch (e) {
125
+ if (process.platform === "win32")
126
+ return;
127
+ throw e;
128
+ }
129
+ try {
130
+ fsyncSync(fd);
131
+ }
132
+ catch (e) {
133
+ const code = e.code;
134
+ if (code !== "EINVAL" && code !== "EPERM" && code !== "ENOTSUP")
135
+ throw e; // a file system without fsync
136
+ }
137
+ finally {
138
+ closeSync(fd);
139
+ }
140
+ }
141
+ const has = (root, name) => existsSync(join(root, name));
142
+ /**
143
+ * Write the three files so that a crash at any point leaves either the old files or a save the next load finishes:
144
+ * all temp files first (flushed), then the marker, then the renames with `okb.json` last, then the old-layout files
145
+ * and the marker are removed. The caller holds the folder's lock (a new folder has no other writer).
146
+ */
102
147
  export function writeGraph(root, manifest, nodes, edges) {
103
148
  const lines = (ls) => (ls.length ? ls.join("\n") + "\n" : "");
104
- const files = [
105
- ["okb.json", JSON.stringify(manifest, null, 2) + "\n"],
106
- [NODES_FILE, lines(nodeLines(nodes))],
107
- [EDGES_FILE, lines(edgeLines(edges))],
108
- ];
109
- for (const [name, text] of files)
110
- writeFileSync(join(root, name + ".tmp"), text, "utf8");
111
- for (const [name] of files)
149
+ const text = {
150
+ [MANIFEST_FILE]: JSON.stringify(manifest, null, 2) + "\n",
151
+ [NODES_FILE]: lines(nodeLines(nodes)),
152
+ [EDGES_FILE]: lines(edgeLines(edges)),
153
+ };
154
+ // A marker left by an interrupted save of an older okb, or one nobody finished, would make the roll-forward below
155
+ // rename these new temp files over a save it doesn't know about. Finish that one first.
156
+ finishSave(root);
157
+ for (const name of SAVE_ORDER) {
158
+ const tmp = join(root, name + ".tmp");
159
+ writeFileSync(tmp, text[name], "utf8");
160
+ flush(tmp);
161
+ }
162
+ saveSeam.at("temps");
163
+ writeFileSync(join(root, SAVING_MARKER), SAVE_ORDER.join("\n") + "\n", "utf8");
164
+ flush(join(root, SAVING_MARKER));
165
+ flush(root);
166
+ saveSeam.at("marker");
167
+ completeSave(root);
168
+ }
169
+ /** Rename the temp files that are left (in order), drop the old-layout files, then remove the marker. Resumable at every step. */
170
+ function completeSave(root) {
171
+ for (const name of SAVE_ORDER) {
172
+ if (!has(root, name + ".tmp"))
173
+ continue;
112
174
  renameSync(join(root, name + ".tmp"), join(root, name));
175
+ saveSeam.at(`renamed:${name}`);
176
+ }
177
+ flush(root);
113
178
  for (const old of [LEGACY_NODES, LEGACY_EDGES])
114
- if (existsSync(join(root, old)))
179
+ if (has(root, old))
115
180
  unlinkSync(join(root, old));
181
+ saveSeam.at("legacy");
182
+ unlinkSync(join(root, SAVING_MARKER));
183
+ saveSeam.at("unmarked");
184
+ }
185
+ /** Whether a save was interrupted after its marker was written (a save in flight looks the same; check the lock). */
186
+ export function saveInterrupted(root) {
187
+ return has(root, SAVING_MARKER);
188
+ }
189
+ /**
190
+ * Finish an interrupted save: a marker means all three temp files were complete, so renaming the ones that are left gives
191
+ * exactly the folder the save would have made. Safe to run again after a crash of its own. The caller holds the lock.
192
+ * The renames go in a fixed order, so the temp files that remain must be a tail of it; anything else (a temp file
193
+ * deleted by hand, say) is not a state a crash makes, and it stops with an error instead of guessing.
194
+ */
195
+ export function finishSave(root) {
196
+ if (!has(root, SAVING_MARKER))
197
+ return;
198
+ const left = SAVE_ORDER.map((name) => has(root, name + ".tmp"));
199
+ const first = left.indexOf(true);
200
+ const missing = first < 0 ? [] : SAVE_ORDER.filter((_, i) => i > first && !left[i]);
201
+ const missingFinal = SAVE_ORDER.filter((name, i) => !left[i] && !has(root, name));
202
+ if (missing.length || missingFinal.length) {
203
+ const tmps = SAVE_ORDER.filter((_, i) => left[i]).map((n) => n + ".tmp");
204
+ throw new OkbError(`The last save of ${root} was interrupted (${SAVING_MARKER} is there), and the files aren't in a state okb can finish: ` +
205
+ `${tmps.length ? `${tmps.join(", ")} left over` : "no temp files left"}, ` +
206
+ `${missing.length ? `${missing.map((n) => n + ".tmp").join(", ")} missing` : ""}${missing.length && missingFinal.length ? ", " : ""}` +
207
+ `${missingFinal.length ? `${missingFinal.join(", ")} missing` : ""}. ` +
208
+ "Nothing was changed. Restore the folder from git or a backup, or fix those files by hand and delete " + SAVING_MARKER + ".");
209
+ }
210
+ completeSave(root);
116
211
  }
package/dist/model.d.ts CHANGED
@@ -32,6 +32,7 @@ export declare class Ontology {
32
32
  get nodes(): readonly OkbNode[];
33
33
  get edges(): readonly GraphEdge[];
34
34
  static load(start: string): Ontology;
35
+ private static recover;
35
36
  private static rootOf;
36
37
  private static read;
37
38
  static fromData(nodes: readonly OkbNode[], edges: readonly GraphEdge[], manifest?: Partial<Manifest>): Ontology;
package/dist/model.js CHANGED
@@ -3,7 +3,7 @@ import { createHash, randomBytes } from "node:crypto";
3
3
  import { existsSync, readFileSync } from "node:fs";
4
4
  import { dirname, join, resolve } from "node:path";
5
5
  import { OkbError } from "./errors.js";
6
- import { compareNatural, readGraph, writeGraph } from "./layout.js";
6
+ import { compareNatural, finishSave, readGraph, saveInterrupted, writeGraph } from "./layout.js";
7
7
  import { acquireLock, isLocked, waitUnlocked } from "./lock.js";
8
8
  import { FORMAT_VERSION } from "./registry.js";
9
9
  import * as naming from "./naming.js";
@@ -60,7 +60,11 @@ export function nodeLabel(n) {
60
60
  /** Every name-like field a node can be looked up by (a quote's text counts: its id has a random tag). */
61
61
  function lookupNames(n) {
62
62
  // A hand-edited file can hold a number or object here; those can't be looked up by name, and must not reach key().
63
- return ["name", "text", "title", "quote"].map((f) => n[f]).filter((v) => typeof v === "string" && v !== "");
63
+ // Positions are fixed (name, text, title, quote): callers slice the first two, so a missing field stays as "".
64
+ return ["name", "text", "title", "quote"].map((f) => {
65
+ const v = n[f];
66
+ return typeof v === "string" ? v : "";
67
+ });
64
68
  }
65
69
  export { isRelationship };
66
70
  export function findRoot(start) {
@@ -116,11 +120,36 @@ export class Ontology {
116
120
  // this was reading, the files may be a mix of old and new, so read again.
117
121
  for (let attempt = 0;; attempt++) {
118
122
  waitUnlocked(root);
123
+ // A marker means a save started and may not have finished. Taking the lock waits out a save still running (it
124
+ // removes the marker before it lets go) and, if the saver is gone, finishes the save under the lock.
125
+ if (saveInterrupted(root)) {
126
+ Ontology.recover(root);
127
+ continue;
128
+ }
119
129
  const ont = Ontology.read(root);
130
+ if (saveInterrupted(root))
131
+ continue; // a save began while we read
120
132
  if (attempt >= 3 || !isLocked(root))
121
133
  return ont;
122
134
  }
123
135
  }
136
+ static recover(root) {
137
+ let release;
138
+ try {
139
+ release = acquireLock(root);
140
+ }
141
+ catch (e) {
142
+ if (e instanceof OkbError)
143
+ throw e;
144
+ throw new OkbError(`The last save of ${root} was interrupted and okb can't finish it: ${e.message}. Run any okb command that changes this folder where you can write to it.`);
145
+ }
146
+ try {
147
+ finishSave(root);
148
+ }
149
+ finally {
150
+ release();
151
+ }
152
+ }
124
153
  /**
125
154
  * Load, change and save one folder with its lock held, so a second command running at the same time
126
155
  * waits instead of overwriting this one's work. `fn` may be async; it should call `save()` itself.
@@ -131,6 +160,7 @@ export class Ontology {
131
160
  const release = acquireLock(root);
132
161
  let result;
133
162
  try {
163
+ finishSave(root); // the lock is ours, so a marker is a save that was interrupted
134
164
  result = fn(Ontology.read(root));
135
165
  }
136
166
  catch (e) {
@@ -416,18 +446,25 @@ export class Ontology {
416
446
  * the same value, so a command that creates a node and edits it afterwards leaves the two
417
447
  * equal. The CLI wraps each command in this; nesting reuses the outer read. A library caller
418
448
  * that calls ops directly without it still gets a fresh read per addNode/touch, which is fine.
449
+ * An async `fn` keeps the read until its promise settles.
419
450
  * @internal
420
451
  */
421
452
  tick(fn) {
422
453
  if (this.opTime !== null)
423
454
  return fn();
424
455
  this.opTime = timestamp();
456
+ let result;
425
457
  try {
426
- return fn();
458
+ result = fn();
427
459
  }
428
- finally {
460
+ catch (e) {
429
461
  this.opTime = null;
462
+ throw e;
430
463
  }
464
+ if (result instanceof Promise)
465
+ return result.finally(() => (this.opTime = null));
466
+ this.opTime = null;
467
+ return result;
431
468
  }
432
469
  /**
433
470
  * Record that something stored ON the node changed (its own fields, property values or
@@ -0,0 +1,90 @@
1
+ import type { Ontology } from "./model.js";
2
+ import type { GraphEdge, NodeType, OkbNode, StoredValue } from "./types.js";
3
+ /** What one operation takes. Only the keys listed here are allowed. */
4
+ export interface FindQuery {
5
+ class: string;
6
+ where?: Record<string, QueryValue | QueryValue[]>;
7
+ }
8
+ export interface TraverseQuery {
9
+ from: string | string[];
10
+ slot: string;
11
+ direction?: "out" | "in";
12
+ depth?: number;
13
+ }
14
+ export interface SlotsQuery {
15
+ of: string;
16
+ }
17
+ export type QueryValue = string | number | boolean;
18
+ /** A query: an object with exactly one of these keys. */
19
+ export type Query = {
20
+ find: FindQuery;
21
+ } | {
22
+ traverse: TraverseQuery;
23
+ } | {
24
+ slots: SlotsQuery;
25
+ };
26
+ /** A node a query returns. */
27
+ export interface NodeHit {
28
+ id: string;
29
+ type: NodeType;
30
+ name: string;
31
+ }
32
+ /** A slot a query returns. */
33
+ export interface SlotHit {
34
+ id: string;
35
+ name: string;
36
+ valueType: string | undefined;
37
+ relationship: boolean;
38
+ }
39
+ /**
40
+ * One value a traversal reaches. `id` and `type` are set when the value is a node (a relationship
41
+ * target); a property value has neither. `from` is the node it was read from and `depth` the hop (1 is
42
+ * direct). `edge` holds the edge properties of a relationship link. `inheritedFrom` is the class whose
43
+ * fixed value this is, when the node states none of its own.
44
+ */
45
+ export interface TraverseHit {
46
+ name: string;
47
+ value: StoredValue;
48
+ id?: string;
49
+ type?: NodeType;
50
+ from: string;
51
+ depth: number;
52
+ edge?: Record<string, unknown>;
53
+ inheritedFrom?: string;
54
+ }
55
+ /** `queryGet`: a node and the edges on both sides of it, as `okb show --json` prints them. */
56
+ export interface GetResult {
57
+ node: OkbNode;
58
+ out: GraphEdge[];
59
+ in: GraphEdge[];
60
+ }
61
+ export type QueryResult = {
62
+ kind: "find";
63
+ hits: NodeHit[];
64
+ } | {
65
+ kind: "traverse";
66
+ hits: TraverseHit[];
67
+ } | {
68
+ kind: "slots";
69
+ hits: SlotHit[];
70
+ };
71
+ /** The most hops a traversal takes. */
72
+ export declare const MAX_DEPTH = 3;
73
+ /** Check a query's shape and return it typed, or throw an `OkbError` saying what is wrong. Names aren't looked up here. */
74
+ export declare function checkQuery(q: unknown): Query;
75
+ /** Run a query. Throws an `OkbError` when its shape is wrong or a name in it doesn't exist. */
76
+ export declare function query(ont: Ontology, q: unknown): QueryResult;
77
+ /** The distinct names in a result, sorted: the list `okb cq answer` compares with `expect`. */
78
+ export declare function resultNames(r: QueryResult): string[];
79
+ /** Instances of a class (and its subclasses) whose slot values match. Every `where` slot must match, and a list means all of its values. */
80
+ export declare function queryFind(ont: Ontology, q: FindQuery): NodeHit[];
81
+ /**
82
+ * What a slot gives from one or more classes or instances. A relationship slot follows its own direction
83
+ * (an inverse slot reads the same edges backwards); `direction: "in"` reads it the other way. `depth` follows
84
+ * the same slot again from each node it reaches, up to 3 hops, never revisiting a node.
85
+ */
86
+ export declare function queryTraverse(ont: Ontology, q: TraverseQuery): TraverseHit[];
87
+ /** The slots a class (own and inherited) or an instance has. */
88
+ export declare function querySlots(ont: Ontology, q: SlotsQuery): SlotHit[];
89
+ /** One node (by id, name or `class:Foo`) with the edges leaving and entering it: the data `okb show --json` prints. */
90
+ export declare function queryGet(ont: Ontology, ref: string): GetResult;
package/dist/query.js ADDED
@@ -0,0 +1,205 @@
1
+ /**
2
+ * The read-only query layer: pure functions above `Ontology` that return typed data, not text.
3
+ *
4
+ * A query is a JSON object with one key, the shapes `okb cq answer` stores (docs/FORMAT.md, "Expected
5
+ * answers"): `find`, `traverse` and `slots`. `queryGet` is the fourth operation, the data `okb show --json`
6
+ * prints. Everything reads through the `Ontology` primitives (`statedValues`, `inheritedFixed`,
7
+ * `applicableSlots`, `rel`), so relationship storage stays in one place. Nothing here writes.
8
+ *
9
+ * Match rules, the choices behind them and what was left out are written down in decision 0034 and in
10
+ * FORMAT.md. Results are sorted by name, and a thing appears once.
11
+ */
12
+ import { OkbError } from "./errors.js";
13
+ import { edgeProps } from "./relationships.js";
14
+ const SHAPES = new Map([
15
+ ["find", ["class", "where"]],
16
+ ["traverse", ["from", "slot", "direction", "depth"]],
17
+ ["slots", ["of"]],
18
+ ]);
19
+ /** The most hops a traversal takes. */
20
+ export const MAX_DEPTH = 3;
21
+ const isObj = (x) => !!x && typeof x === "object" && !Array.isArray(x);
22
+ // okb's cq compare (packages/okb/src/cqanswer.ts) normalizes names the same way; keep the two definitions equal.
23
+ const norm = (s) => s.trim().toLowerCase();
24
+ /** One collation for every result, so `--json` order and cq names don't change with the process's LANG. */
25
+ const collator = new Intl.Collator("en");
26
+ const byText = (a, b) => collator.compare(a, b) || (a < b ? -1 : a > b ? 1 : 0);
27
+ /** By name, then id (a property value has none, so it sorts as ""). */
28
+ const byName = (a, b) => byText(a.name, b.name) || byText(a.id ?? "", b.id ?? "");
29
+ /** Check a query's shape and return it typed, or throw an `OkbError` saying what is wrong. Names aren't looked up here. */
30
+ export function checkQuery(q) {
31
+ const keys = isObj(q) ? Object.keys(q) : [];
32
+ if (!isObj(q) || keys.length !== 1 || !SHAPES.has(keys[0]))
33
+ throw new OkbError(`A query is an object with one key: ${[...SHAPES.keys()].join(", ")}. Example: {"traverse":{"from":"Chateau Morgon","slot":"produces"}}`);
34
+ const kind = keys[0];
35
+ const allowed = SHAPES.get(kind);
36
+ const body = q[kind];
37
+ if (!isObj(body))
38
+ throw new OkbError(`"${kind}" must be an object with ${allowed.join(", ")}.`);
39
+ const unknown = Object.keys(body).filter((k) => !allowed.includes(k));
40
+ if (unknown.length)
41
+ throw new OkbError(`"${kind}" doesn't take ${unknown.map((k) => `"${k}"`).join(", ")}. It takes ${allowed.join(", ")}.`);
42
+ const name = (k) => {
43
+ if (body[k] === undefined)
44
+ throw new OkbError(`"${kind}" needs "${k}".`);
45
+ if (typeof body[k] !== "string" || !body[k])
46
+ throw new OkbError(`"${kind}.${k}" must be a name (text).`);
47
+ };
48
+ if (kind === "find") {
49
+ name("class");
50
+ const w = body.where;
51
+ if (w !== undefined) {
52
+ if (!isObj(w))
53
+ throw new OkbError(`"find.where" must be an object of slot: value.`);
54
+ for (const [slot, v] of Object.entries(w)) {
55
+ const vals = Array.isArray(v) ? v : [v];
56
+ if (!vals.length || !vals.every((x) => ["string", "number", "boolean"].includes(typeof x)))
57
+ throw new OkbError(`"find.where.${slot}" must be a value or a list of values.`);
58
+ }
59
+ }
60
+ }
61
+ else if (kind === "traverse") {
62
+ name("slot");
63
+ const from = body.from;
64
+ if (from === undefined)
65
+ throw new OkbError(`"traverse" needs "from".`);
66
+ if (!(typeof from === "string" && from) && !(Array.isArray(from) && from.length && from.every((x) => typeof x === "string" && x)))
67
+ throw new OkbError(`"traverse.from" must be a name (text) or a list of names.`);
68
+ if (body.direction !== undefined && body.direction !== "out" && body.direction !== "in")
69
+ throw new OkbError(`"traverse.direction" must be "out" or "in".`);
70
+ const d = body.depth;
71
+ if (d !== undefined && (!Number.isInteger(d) || d < 1 || d > MAX_DEPTH))
72
+ throw new OkbError(`"traverse.depth" must be a whole number from 1 to ${MAX_DEPTH}.`);
73
+ }
74
+ else
75
+ name("of");
76
+ return q;
77
+ }
78
+ /** Run a query. Throws an `OkbError` when its shape is wrong or a name in it doesn't exist. */
79
+ export function query(ont, q) {
80
+ const checked = checkQuery(q);
81
+ if ("find" in checked)
82
+ return { kind: "find", hits: queryFind(ont, checked.find) };
83
+ if ("traverse" in checked)
84
+ return { kind: "traverse", hits: queryTraverse(ont, checked.traverse) };
85
+ return { kind: "slots", hits: querySlots(ont, checked.slots) };
86
+ }
87
+ /** The distinct names in a result, sorted: the list `okb cq answer` compares with `expect`. */
88
+ export function resultNames(r) {
89
+ return [...new Set(r.hits.map((h) => h.name))].sort(byText);
90
+ }
91
+ const hit = (ont, id) => {
92
+ const n = ont.require(id);
93
+ return { id, type: n.type, name: ont.label(id) };
94
+ };
95
+ /**
96
+ * A node's own values for a slot, else what a class fixes for it. Relationship values are node ids; the rest are literals.
97
+ * Only edges leaving a class are inherited, so reading in reverse never falls back to the class.
98
+ */
99
+ function read(ont, id, slotId, reverse) {
100
+ const stated = (n) => (reverse ? flipped(ont, n, slotId) : ont.statedValues(n, slotId));
101
+ const own = stated(id);
102
+ if (own.length || reverse)
103
+ return { values: own };
104
+ for (const c of ont.classContext(id)) {
105
+ if (c === id)
106
+ continue;
107
+ const vals = stated(c);
108
+ if (vals.length)
109
+ return { values: vals, inheritedFrom: c };
110
+ }
111
+ return { values: [] };
112
+ }
113
+ /** Literal values plus the relationship read the other way round than the slot says. */
114
+ function flipped(ont, id, slotId) {
115
+ const spec = ont.rel.spec(slotId);
116
+ if (!spec)
117
+ return ont.statedValues(id, slotId);
118
+ return spec.reverse ? ont.targets(id, spec.type) : ont.sources(id, spec.type);
119
+ }
120
+ /** Instances of a class (and its subclasses) whose slot values match. Every `where` slot must match, and a list means all of its values. */
121
+ export function queryFind(ont, q) {
122
+ const cls = ont.find(q.class, "Class");
123
+ const where = Object.entries(q.where ?? {}).map(([slot, v]) => ({
124
+ id: ont.find(slot, "Slot").id,
125
+ relationship: ont.rel.spec(ont.find(slot, "Slot").id) !== null,
126
+ want: (Array.isArray(v) ? v : [v]).map((x) => String(x)),
127
+ }));
128
+ const matches = (id, w) => {
129
+ const have = read(ont, id, w.id, false).values.map((v) => norm(valueName(ont, v, w.relationship)));
130
+ // "*" is "has any value".
131
+ return w.want.every((x) => (x === "*" ? have.length > 0 : have.includes(norm(x))));
132
+ };
133
+ const out = ont.ofType("Instance")
134
+ .filter((i) => ont.instanceClasses(i.id).has(cls.id))
135
+ .filter((i) => where.every((w) => matches(i.id, w)))
136
+ .map((i) => hit(ont, i.id));
137
+ return out.sort(byName);
138
+ }
139
+ /** What a stored value is called: the label of the node it points at when the slot is a relationship, else its text. */
140
+ const valueName = (ont, v, relationship) => (relationship && typeof v === "string" && ont.get(v) ? ont.label(v) : String(v));
141
+ /**
142
+ * What a slot gives from one or more classes or instances. A relationship slot follows its own direction
143
+ * (an inverse slot reads the same edges backwards); `direction: "in"` reads it the other way. `depth` follows
144
+ * the same slot again from each node it reaches, up to 3 hops, never revisiting a node.
145
+ */
146
+ export function queryTraverse(ont, q) {
147
+ const found = (Array.isArray(q.from) ? q.from : [q.from]).map((f) => ont.find(f, ["Class", "Instance"]));
148
+ const starts = found.filter((s, i) => found.findIndex((o) => o.id === s.id) === i);
149
+ const slot = ont.find(q.slot, "Slot");
150
+ const depth = q.depth ?? 1;
151
+ const spec = ont.rel.spec(slot.id);
152
+ const relationship = spec !== null;
153
+ if ((depth > 1 || q.direction) && !relationship)
154
+ throw new OkbError(`"${slot.name}" is a property, so it has no direction or hops. Only a relationship can be followed more than once.`);
155
+ const reverse = q.direction === "in";
156
+ const hits = [];
157
+ const seen = new Set(starts.map((s) => s.id));
158
+ let frontier = starts.map((s) => s.id);
159
+ for (let level = 1; level <= depth && frontier.length; level++) {
160
+ const next = [];
161
+ for (const id of frontier) {
162
+ const { values, inheritedFrom } = read(ont, id, slot.id, reverse);
163
+ for (const v of values) {
164
+ const node = relationship && typeof v === "string" ? ont.get(v) : undefined;
165
+ const h = { name: valueName(ont, v, relationship), value: v, from: id, depth: level };
166
+ if (node) {
167
+ h.id = node.id;
168
+ h.type = node.type;
169
+ const e = spec && edgeBetween(ont, inheritedFrom ?? id, node.id, spec.type, spec.reverse !== reverse);
170
+ if (e) {
171
+ const p = edgeProps(e);
172
+ if (Object.keys(p).length)
173
+ h.edge = p;
174
+ }
175
+ if (!seen.has(node.id)) {
176
+ seen.add(node.id);
177
+ next.push(node.id);
178
+ }
179
+ }
180
+ if (inheritedFrom)
181
+ h.inheritedFrom = inheritedFrom;
182
+ hits.push(h);
183
+ }
184
+ }
185
+ frontier = next;
186
+ }
187
+ return hits.sort((a, b) => a.depth - b.depth || byName(a, b));
188
+ }
189
+ function edgeBetween(ont, id, other, type, reverse) {
190
+ const [from, to] = reverse ? [other, id] : [id, other];
191
+ return ont.outEdges(from, type).find((e) => e.to === to);
192
+ }
193
+ /** The slots a class (own and inherited) or an instance has. */
194
+ export function querySlots(ont, q) {
195
+ const of = ont.find(q.of, ["Class", "Instance"]);
196
+ return ont.applicableSlots(of.id)
197
+ .map((id) => ont.require(id, "Slot"))
198
+ .map((s) => ({ id: s.id, name: ont.label(s.id), valueType: s.valueType, relationship: ont.rel.spec(s.id) !== null }))
199
+ .sort(byName);
200
+ }
201
+ /** One node (by id, name or `class:Foo`) with the edges leaving and entering it: the data `okb show --json` prints. */
202
+ export function queryGet(ont, ref) {
203
+ const node = ont.find(ref);
204
+ return { node, out: ont.edges.filter((e) => e.from === node.id), in: ont.edges.filter((e) => e.to === node.id) };
205
+ }
package/dist/types.d.ts CHANGED
@@ -94,6 +94,12 @@ export interface CompetencyQuestionNode extends Stamps {
94
94
  id: string;
95
95
  text: string;
96
96
  status?: "draft" | "answerable";
97
+ /** The stored expected answer (`okb cq answer`): a declarative query, the names it should return, and how strictly to compare. */
98
+ answer?: {
99
+ query: Record<string, unknown>;
100
+ expect: string[];
101
+ match?: "exact" | "includes";
102
+ };
97
103
  }
98
104
  export interface TermNode extends Stamps {
99
105
  type: "Term";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ontology-kit/reader",
3
- "version": "0.3.0-alpha.210",
3
+ "version": "0.3.0-alpha.66",
4
4
  "license": "MIT",
5
5
  "description": "Read the okb file format: an ontology folder's typed nodes and edges, loading with migrations, the reserved edge types and relationship values. No CLI, no meta-KB.",
6
6
  "homepage": "https://ontology-kit.dev",