@mark1russell7/ontology 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +119 -2
- package/build/generate-Dv-t-uia.mjs +819 -0
- package/build/generate-Dv-t-uia.mjs.map +1 -0
- package/build/header-BluJvnVP.d.mts +394 -0
- package/build/index.d.mts +175 -0
- package/build/index.mjs +303 -0
- package/build/index.mjs.map +1 -0
- package/build/node.d.mts +8 -0
- package/build/node.mjs +23 -0
- package/build/node.mjs.map +1 -0
- package/package.json +71 -3
|
@@ -0,0 +1,819 @@
|
|
|
1
|
+
import { valueIn, whyNotConvertible } from "@mark1russell7/quantity";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { isQuantitySchema } from "@mark1russell7/quantity/schema";
|
|
4
|
+
// src/grammar.ts
|
|
5
|
+
/** The modes of being, in the order of `Mode`. */
|
|
6
|
+
const MODES = [
|
|
7
|
+
"top",
|
|
8
|
+
"continuant",
|
|
9
|
+
"occurrent",
|
|
10
|
+
"abstract",
|
|
11
|
+
"information",
|
|
12
|
+
"relation"
|
|
13
|
+
];
|
|
14
|
+
/** The scopes of a record, from the least sensitive to the most sensitive. */
|
|
15
|
+
const SCOPES = [
|
|
16
|
+
"public",
|
|
17
|
+
"shared",
|
|
18
|
+
"private",
|
|
19
|
+
"intimate"
|
|
20
|
+
];
|
|
21
|
+
/** The schema of a scope. */
|
|
22
|
+
const scopeSchema = z.enum(SCOPES);
|
|
23
|
+
/**
|
|
24
|
+
* The rank of each scope. The scopes are an order, not a set. An audience sees each scope at its rank or below.
|
|
25
|
+
* A record that comes from a more sensitive record gets the more sensitive scope.
|
|
26
|
+
*/
|
|
27
|
+
const SCOPE_RANK = {
|
|
28
|
+
public: 0,
|
|
29
|
+
shared: 1,
|
|
30
|
+
private: 2,
|
|
31
|
+
intimate: 3
|
|
32
|
+
};
|
|
33
|
+
/** This function gives the rank of a scope: 0 for `public`, 3 for `intimate`. */
|
|
34
|
+
const scopeRank = (scope) => SCOPE_RANK[scope];
|
|
35
|
+
/** This function gives the more sensitive of two scopes. */
|
|
36
|
+
const maxScope = (a, b) => SCOPE_RANK[a] >= SCOPE_RANK[b] ? a : b;
|
|
37
|
+
/** This function tells if an audience at the scope `audience` can see a record at the scope `scope`. */
|
|
38
|
+
const visibleTo = (scope, audience) => SCOPE_RANK[scope] <= SCOPE_RANK[audience];
|
|
39
|
+
/** The form of the name of a kind, a relation kind, a facet or a role. */
|
|
40
|
+
const NAME_PATTERN = /^[a-z0-9][a-z0-9-]*$/;
|
|
41
|
+
/** The form of the id of an entity: two or more names, with a dot between each two. */
|
|
42
|
+
const ENTITY_ID_PATTERN = /^[a-z0-9][a-z0-9-]*(\.[a-z0-9][a-z0-9-]*)+$/;
|
|
43
|
+
/** The schema of the id of an entity. */
|
|
44
|
+
const entityIdSchema = z.string().regex(ENTITY_ID_PATTERN);
|
|
45
|
+
const isoDateTime = z.iso.datetime({ offset: true });
|
|
46
|
+
/** This function gives the name of an entity: its attribute `name` when it is a string, or else its id. */
|
|
47
|
+
const nameOf = (entity) => {
|
|
48
|
+
const name = entity.attrs["name"];
|
|
49
|
+
return typeof name === "string" ? name : entity.id;
|
|
50
|
+
};
|
|
51
|
+
/** This function gives the FNV-1a hash of 64 bits of a text, in hexadecimal. It is the same in Node.js and a browser. */
|
|
52
|
+
const fnv1a64 = (text) => {
|
|
53
|
+
let hash = 14695981039346656037n;
|
|
54
|
+
for (const byte of new TextEncoder().encode(text)) {
|
|
55
|
+
hash ^= BigInt(byte);
|
|
56
|
+
hash = hash * 1099511628211n & 18446744073709551615n;
|
|
57
|
+
}
|
|
58
|
+
return hash.toString(16).padStart(16, "0");
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* This function gives the id of a relation instance from its kind and its two ends. The same fact always gets
|
|
62
|
+
* the same id. A symmetric kind sorts its two ends first, so each pair has one relation.
|
|
63
|
+
*
|
|
64
|
+
* @remarks
|
|
65
|
+
* A space joins the two ends, and no entity id contains a space. A kind with a key of more parts gets its id from
|
|
66
|
+
* `keyedRelationId`, through `Registry.relationIdOf`.
|
|
67
|
+
*/
|
|
68
|
+
const relationId = (type, from, to, symmetric = false) => {
|
|
69
|
+
const [a, b] = symmetric && to < from ? [to, from] : [from, to];
|
|
70
|
+
return `rel.${type}.${fnv1a64(`${a} ${b}`)}`;
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* This function gives the id of a relation whose key has more parts than its two ends. The hash is of the parts
|
|
74
|
+
* of the key, as name and value, in the order of the key.
|
|
75
|
+
*
|
|
76
|
+
* @remarks
|
|
77
|
+
* The JSON of the parts starts with a bracket, and no entity id does. Thus the id is not an id of `relationId` at any time.
|
|
78
|
+
*/
|
|
79
|
+
const keyedRelationId = (type, parts) => `rel.${type}.${fnv1a64(JSON.stringify(parts))}`;
|
|
80
|
+
/** This function tells if an id is the id of a relation instance. */
|
|
81
|
+
const isRelationId = (id) => id.startsWith("rel.");
|
|
82
|
+
/**
|
|
83
|
+
* The schema of an envelope. A record has `superseded_by` or `retired_from`, not the two. The time `valid_from`
|
|
84
|
+
* is not after `valid_to`.
|
|
85
|
+
*/
|
|
86
|
+
const envelopeSchema = z.strictObject({
|
|
87
|
+
valid_from: isoDateTime.optional(),
|
|
88
|
+
valid_to: isoDateTime.optional(),
|
|
89
|
+
observed_at: isoDateTime.optional(),
|
|
90
|
+
recorded_at: isoDateTime.optional(),
|
|
91
|
+
source_ids: z.array(z.string()).optional(),
|
|
92
|
+
derived: z.boolean().optional(),
|
|
93
|
+
confidence: z.number().min(0).max(1).optional(),
|
|
94
|
+
attribution: z.string().optional(),
|
|
95
|
+
scope: scopeSchema.optional(),
|
|
96
|
+
superseded_by: entityIdSchema.optional(),
|
|
97
|
+
retired_from: entityIdSchema.optional()
|
|
98
|
+
}).refine((e) => e.superseded_by === void 0 || e.retired_from === void 0, { message: "superseded_by and retired_from are mutually exclusive" }).refine((e) => e.valid_from === void 0 || e.valid_to === void 0 || e.valid_from <= e.valid_to, { message: "valid_from must not be after valid_to" });
|
|
99
|
+
/** The schema of an entity, before the check of its kind. */
|
|
100
|
+
const entitySchema = z.strictObject({
|
|
101
|
+
id: entityIdSchema,
|
|
102
|
+
kind: z.string().regex(NAME_PATTERN),
|
|
103
|
+
attrs: z.record(z.string(), z.unknown()),
|
|
104
|
+
envelope: envelopeSchema.default({})
|
|
105
|
+
});
|
|
106
|
+
const roleFillersSchema = z.record(z.string().regex(NAME_PATTERN), z.union([entityIdSchema, z.array(entityIdSchema)]));
|
|
107
|
+
/** The schema of an edge as a writer gives it. */
|
|
108
|
+
const edgeSchema = z.strictObject({
|
|
109
|
+
id: entityIdSchema.optional(),
|
|
110
|
+
from: entityIdSchema,
|
|
111
|
+
type: z.string().regex(NAME_PATTERN),
|
|
112
|
+
to: entityIdSchema,
|
|
113
|
+
roles: roleFillersSchema.optional(),
|
|
114
|
+
qualifiers: z.record(z.string(), z.unknown()).default({}),
|
|
115
|
+
envelope: envelopeSchema.default({})
|
|
116
|
+
});
|
|
117
|
+
/** The schema of an edge as a store gives it back: always with its id, and with `inverse` on a second row. */
|
|
118
|
+
const edgeRowSchema = z.strictObject({
|
|
119
|
+
id: entityIdSchema,
|
|
120
|
+
from: entityIdSchema,
|
|
121
|
+
type: z.string().regex(NAME_PATTERN),
|
|
122
|
+
to: entityIdSchema,
|
|
123
|
+
roles: roleFillersSchema.optional(),
|
|
124
|
+
qualifiers: z.record(z.string(), z.unknown()),
|
|
125
|
+
envelope: envelopeSchema,
|
|
126
|
+
inverse: z.literal(true).optional()
|
|
127
|
+
});
|
|
128
|
+
// src/registry.ts
|
|
129
|
+
/** The name of the kind above each relation kind. */
|
|
130
|
+
const RELATION_ROOT = "relation";
|
|
131
|
+
/** The key of a relation kind that names no key: its two ends. */
|
|
132
|
+
const ENDS_KEY = ["from", "to"];
|
|
133
|
+
/** The error of a registry that is not correct, or of a record that the registry refuses. */
|
|
134
|
+
var RegistryError = class extends Error {
|
|
135
|
+
issues;
|
|
136
|
+
constructor(message, issues = []) {
|
|
137
|
+
const detail = issues.map((i) => ` ${i.path}: ${i.message}`).join("\n");
|
|
138
|
+
super(detail.length > 0 ? `${message}\n${detail}` : message);
|
|
139
|
+
this.name = "RegistryError";
|
|
140
|
+
this.issues = issues;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
const zodIssues = (prefix, error) => error.issues.map((issue) => ({
|
|
144
|
+
path: issue.path.length > 0 ? `${prefix}.${issue.path.join(".")}` : prefix,
|
|
145
|
+
message: issue.message
|
|
146
|
+
}));
|
|
147
|
+
/**
|
|
148
|
+
* This function joins the parts of a core and its add-ons into one input of a registry. The registry refuses a
|
|
149
|
+
* kind, a relation kind or a facet that two parts declare.
|
|
150
|
+
*/
|
|
151
|
+
const composeRegistryInput = (...parts) => ({
|
|
152
|
+
kinds: parts.flatMap((part) => part.kinds),
|
|
153
|
+
relations: parts.flatMap((part) => part.relations),
|
|
154
|
+
facets: parts.flatMap((part) => part.facets ?? []),
|
|
155
|
+
namedReferences: parts.flatMap((part) => part.namedReferences ?? []),
|
|
156
|
+
deadlines: parts.flatMap((part) => part.deadlines ?? []),
|
|
157
|
+
extensions: parts.flatMap((part) => part.extensions ?? [])
|
|
158
|
+
});
|
|
159
|
+
/** This function adds the kinds of the extensions to the ends of the relation kinds. A kind is not added two times. */
|
|
160
|
+
const extend = (relations, extensions) => {
|
|
161
|
+
for (const extension of extensions) {
|
|
162
|
+
const relation = relations.get(extension.relation);
|
|
163
|
+
if (relation === void 0) throw new RegistryError(`an extension names unknown relation kind ${extension.relation}`);
|
|
164
|
+
const add = (ends, more) => [...ends, ...(more ?? []).filter((kind, at, all) => !ends.includes(kind) && all.indexOf(kind) === at)];
|
|
165
|
+
relations.set(relation.name, {
|
|
166
|
+
...relation,
|
|
167
|
+
from: add(relation.from, extension.from),
|
|
168
|
+
to: add(relation.to, extension.to)
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
/**
|
|
173
|
+
* A registry of kinds, relation kinds and facets. It checks itself when it is made, and it checks each entity and
|
|
174
|
+
* each edge.
|
|
175
|
+
*/
|
|
176
|
+
var Registry = class {
|
|
177
|
+
kinds;
|
|
178
|
+
relations;
|
|
179
|
+
facets;
|
|
180
|
+
namedReferences;
|
|
181
|
+
deadlines;
|
|
182
|
+
rootKind;
|
|
183
|
+
schemaCache = /* @__PURE__ */ new Map();
|
|
184
|
+
closureCache = /* @__PURE__ */ new Map();
|
|
185
|
+
/** @throws RegistryError when the parts of the registry are not correct */
|
|
186
|
+
constructor(input) {
|
|
187
|
+
const kinds = /* @__PURE__ */ new Map();
|
|
188
|
+
for (const kind of input.kinds) {
|
|
189
|
+
if (!NAME_PATTERN.test(kind.name)) throw new RegistryError(`invalid kind name: ${kind.name}`);
|
|
190
|
+
if (kinds.has(kind.name)) throw new RegistryError(`duplicate kind: ${kind.name}`);
|
|
191
|
+
kinds.set(kind.name, kind);
|
|
192
|
+
}
|
|
193
|
+
const facets = /* @__PURE__ */ new Map();
|
|
194
|
+
for (const facet of input.facets ?? []) {
|
|
195
|
+
if (!NAME_PATTERN.test(facet.name)) throw new RegistryError(`invalid facet name: ${facet.name}`);
|
|
196
|
+
if (facets.has(facet.name)) throw new RegistryError(`duplicate facet: ${facet.name}`);
|
|
197
|
+
facets.set(facet.name, facet);
|
|
198
|
+
}
|
|
199
|
+
const relations = /* @__PURE__ */ new Map();
|
|
200
|
+
for (const relation of input.relations) {
|
|
201
|
+
if (!NAME_PATTERN.test(relation.name)) throw new RegistryError(`invalid relation kind name: ${relation.name}`);
|
|
202
|
+
if (relations.has(relation.name)) throw new RegistryError(`duplicate relation kind: ${relation.name}`);
|
|
203
|
+
if (kinds.has(relation.name)) throw new RegistryError(`relation kind ${relation.name} collides with a kind`);
|
|
204
|
+
const qualifiers = Object.keys(relation.qualifiers ?? {});
|
|
205
|
+
for (const [role, def] of Object.entries(relation.roles ?? {})) {
|
|
206
|
+
if (!NAME_PATTERN.test(role)) throw new RegistryError(`relation kind ${relation.name}: invalid role name ${role}`);
|
|
207
|
+
if (qualifiers.includes(role)) throw new RegistryError(`relation kind ${relation.name}: ${role} is both a role and a qualifier`);
|
|
208
|
+
if (def.kinds.length === 0) throw new RegistryError(`relation kind ${relation.name}: role ${role} names no kind`);
|
|
209
|
+
}
|
|
210
|
+
relations.set(relation.name, relation);
|
|
211
|
+
}
|
|
212
|
+
extend(relations, input.extensions ?? []);
|
|
213
|
+
for (const relation of relations.values()) {
|
|
214
|
+
const known = (name) => kinds.has(name) || relations.has(name);
|
|
215
|
+
for (const kindName of [...relation.from, ...relation.to]) if (!known(kindName)) throw new RegistryError(`relation kind ${relation.name} references unknown kind ${kindName}`);
|
|
216
|
+
for (const [role, def] of Object.entries(relation.roles ?? {})) for (const kindName of def.kinds) if (!known(kindName)) throw new RegistryError(`relation kind ${relation.name}: role ${role} references unknown kind ${kindName}`);
|
|
217
|
+
}
|
|
218
|
+
if (relations.size > 0 && !kinds.has("relation")) throw new RegistryError(`relation kinds need the ${RELATION_ROOT} kind to descend from`);
|
|
219
|
+
for (const relation of relations.values()) if (relation.parent !== void 0 && !relations.has(relation.parent)) throw new RegistryError(`relation kind ${relation.name} narrows ${relation.parent}, which is not a relation kind`);
|
|
220
|
+
for (const relation of relations.values()) {
|
|
221
|
+
const roles = Object.fromEntries(Object.entries(relation.roles ?? {}).map(([role, def]) => [role, def.many === true ? z.array(entityIdSchema).min(1).optional() : entityIdSchema.optional()]));
|
|
222
|
+
kinds.set(relation.name, {
|
|
223
|
+
name: relation.name,
|
|
224
|
+
parent: relation.parent ?? "relation",
|
|
225
|
+
mode: "relation",
|
|
226
|
+
description: relation.description,
|
|
227
|
+
attributes: {
|
|
228
|
+
...relation.qualifiers ?? {},
|
|
229
|
+
...roles
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
const roots = [];
|
|
234
|
+
for (const kind of kinds.values()) {
|
|
235
|
+
if (kind.parent === null) roots.push(kind.name);
|
|
236
|
+
else if (!kinds.has(kind.parent)) throw new RegistryError(`kind ${kind.name} has unknown parent ${kind.parent}`);
|
|
237
|
+
for (const facet of kind.facets ?? []) if (!facets.has(facet)) throw new RegistryError(`kind ${kind.name} declares unknown facet ${facet}`);
|
|
238
|
+
}
|
|
239
|
+
const root = roots[0];
|
|
240
|
+
if (root === void 0 || roots.length !== 1) throw new RegistryError(`expected exactly one root kind, found: ${roots.join(", ")}`);
|
|
241
|
+
for (const kind of kinds.values()) {
|
|
242
|
+
const seen = /* @__PURE__ */ new Set([kind.name]);
|
|
243
|
+
let current = kind.parent;
|
|
244
|
+
while (current !== null) {
|
|
245
|
+
if (seen.has(current)) throw new RegistryError(`kind cycle through ${current}`);
|
|
246
|
+
seen.add(current);
|
|
247
|
+
current = kinds.get(current)?.parent ?? null;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
for (const reference of input.namedReferences ?? []) {
|
|
251
|
+
if (!relations.has(reference.relation)) throw new RegistryError(`named reference ${reference.attribute} draws unknown relation kind ${reference.relation}`);
|
|
252
|
+
if (!kinds.has(reference.toKind)) throw new RegistryError(`named reference ${reference.attribute} names unknown kind ${reference.toKind}`);
|
|
253
|
+
}
|
|
254
|
+
this.kinds = kinds;
|
|
255
|
+
this.relations = this.inherit(relations);
|
|
256
|
+
this.facets = facets;
|
|
257
|
+
if (relations.size > 0) {
|
|
258
|
+
const inherited = this.effectiveShape(RELATION_ROOT);
|
|
259
|
+
for (const relation of relations.values()) for (const [what, names] of [["qualifier", Object.keys(relation.qualifiers ?? {})], ["role", Object.keys(relation.roles ?? {})]]) for (const name of names) if (name in inherited) throw new RegistryError(`relation kind ${relation.name} declares ${what} ${name}, which every relation instance already has`);
|
|
260
|
+
}
|
|
261
|
+
for (const kind of kinds.values()) {
|
|
262
|
+
const shape = this.effectiveShape(kind.name);
|
|
263
|
+
for (const requirement of kind.requirements ?? []) {
|
|
264
|
+
const names = [...Object.keys(requirement.when), ...requirement.then];
|
|
265
|
+
if (Object.keys(requirement.when).length === 0 || requirement.then.length === 0) throw new RegistryError(`kind ${kind.name}: a requirement needs a when and a then`);
|
|
266
|
+
for (const name of names) if (!(name in shape)) throw new RegistryError(`kind ${kind.name}: a requirement names unknown attribute ${name}`);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
for (const deadline of input.deadlines ?? []) {
|
|
270
|
+
if (!kinds.has(deadline.kind)) throw new RegistryError(`deadline ${deadline.attribute} is on unknown kind ${deadline.kind}`);
|
|
271
|
+
if (deadline.after !== void 0) {
|
|
272
|
+
const why = whyNotConvertible(deadline.after.unit, "d");
|
|
273
|
+
const days = why === void 0 ? valueIn(deadline.after, "d") : NaN;
|
|
274
|
+
if (!Number.isInteger(days)) throw new RegistryError(`deadline ${deadline.attribute} on ${deadline.kind}: after must be whole days${why === void 0 ? "" : ` (${why})`}`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
this.namedReferences = input.namedReferences ?? [];
|
|
278
|
+
this.deadlines = input.deadlines ?? [];
|
|
279
|
+
this.rootKind = root;
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* This method gives each relation kind with the parts that it gets from the kinds that it narrows. A child makes
|
|
283
|
+
* the ends of its parent narrower, and it adds qualifiers and roles. It does not declare a part of its parent again.
|
|
284
|
+
* It gets the key, the symmetry and the transitivity of its parent when it does not declare them.
|
|
285
|
+
*/
|
|
286
|
+
inherit(declared) {
|
|
287
|
+
const merged = /* @__PURE__ */ new Map();
|
|
288
|
+
const resolve = (name) => {
|
|
289
|
+
const done = merged.get(name);
|
|
290
|
+
if (done !== void 0) return done;
|
|
291
|
+
const own = declared.get(name);
|
|
292
|
+
if (own === void 0) throw new RegistryError(`unknown relation kind: ${name}`);
|
|
293
|
+
let effective = own;
|
|
294
|
+
if (own.parent !== void 0) {
|
|
295
|
+
const parent = resolve(own.parent);
|
|
296
|
+
for (const [end, mine, theirs] of [[
|
|
297
|
+
"from",
|
|
298
|
+
own.from,
|
|
299
|
+
parent.from
|
|
300
|
+
], [
|
|
301
|
+
"to",
|
|
302
|
+
own.to,
|
|
303
|
+
parent.to
|
|
304
|
+
]]) for (const kind of mine) if (!theirs.some((wider) => this.isSubkindOf(kind, wider))) throw new RegistryError(`relation kind ${name}: ${end} kind ${kind} is wider than ${own.parent} allows (${theirs.join("|")})`);
|
|
305
|
+
const fields = [...Object.keys(parent.qualifiers ?? {}), ...Object.keys(parent.roles ?? {})];
|
|
306
|
+
for (const field of [...Object.keys(own.qualifiers ?? {}), ...Object.keys(own.roles ?? {})]) if (fields.includes(field)) throw new RegistryError(`relation kind ${name} redeclares ${field}, which it has from ${own.parent}`);
|
|
307
|
+
const qualifiers = {
|
|
308
|
+
...parent.qualifiers ?? {},
|
|
309
|
+
...own.qualifiers ?? {}
|
|
310
|
+
};
|
|
311
|
+
const roles = {
|
|
312
|
+
...parent.roles ?? {},
|
|
313
|
+
...own.roles ?? {}
|
|
314
|
+
};
|
|
315
|
+
const key = own.key ?? parent.key;
|
|
316
|
+
const symmetric = own.symmetric ?? parent.symmetric;
|
|
317
|
+
const transitive = own.transitive ?? parent.transitive;
|
|
318
|
+
effective = {
|
|
319
|
+
...own,
|
|
320
|
+
...Object.keys(qualifiers).length > 0 ? { qualifiers } : {},
|
|
321
|
+
...Object.keys(roles).length > 0 ? { roles } : {},
|
|
322
|
+
...key !== void 0 ? { key } : {},
|
|
323
|
+
...symmetric !== void 0 ? { symmetric } : {},
|
|
324
|
+
...transitive !== void 0 ? { transitive } : {}
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
const key = effective.key ?? ENDS_KEY;
|
|
328
|
+
if (key.length === 0 || new Set(key).size !== key.length) throw new RegistryError(`relation kind ${name}: a key names each part once`);
|
|
329
|
+
for (const part of key) {
|
|
330
|
+
const role = effective.roles?.[part];
|
|
331
|
+
if (!(part === "from" || part === "to" || Object.keys(effective.qualifiers ?? {}).includes(part) || role !== void 0 && role.many !== true)) throw new RegistryError(`relation kind ${name}: key part ${part} is not an end, a single role or a qualifier`);
|
|
332
|
+
}
|
|
333
|
+
merged.set(name, effective);
|
|
334
|
+
return effective;
|
|
335
|
+
};
|
|
336
|
+
for (const name of declared.keys()) resolve(name);
|
|
337
|
+
return merged;
|
|
338
|
+
}
|
|
339
|
+
/**
|
|
340
|
+
* This method gives the kinds from the root to the kind, in that order.
|
|
341
|
+
*
|
|
342
|
+
* @throws RegistryError when a kind is not known
|
|
343
|
+
*/
|
|
344
|
+
ancestry(kindName) {
|
|
345
|
+
const chain = [];
|
|
346
|
+
let current = kindName;
|
|
347
|
+
while (current !== null) {
|
|
348
|
+
const kind = this.kinds.get(current);
|
|
349
|
+
if (kind === void 0) throw new RegistryError(`unknown kind: ${current}`);
|
|
350
|
+
chain.unshift(kind);
|
|
351
|
+
current = kind.parent;
|
|
352
|
+
}
|
|
353
|
+
return chain;
|
|
354
|
+
}
|
|
355
|
+
/** This method tells if a kind is the ancestor kind or a subkind of it. */
|
|
356
|
+
isSubkindOf(kindName, ancestorName) {
|
|
357
|
+
return this.ancestry(kindName).some((kind) => kind.name === ancestorName);
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* This method gives the kind and each of its subkinds.
|
|
361
|
+
*
|
|
362
|
+
* @throws RegistryError when the kind is not known
|
|
363
|
+
*/
|
|
364
|
+
subkindClosure(kindName) {
|
|
365
|
+
const cached = this.closureCache.get(kindName);
|
|
366
|
+
if (cached !== void 0) return cached;
|
|
367
|
+
if (!this.kinds.has(kindName)) throw new RegistryError(`unknown kind: ${kindName}`);
|
|
368
|
+
const closure = /* @__PURE__ */ new Set();
|
|
369
|
+
for (const kind of this.kinds.keys()) if (this.isSubkindOf(kind, kindName)) closure.add(kind);
|
|
370
|
+
this.closureCache.set(kindName, closure);
|
|
371
|
+
return closure;
|
|
372
|
+
}
|
|
373
|
+
/** This method gives the ladder of a kind: its own ladder, or the ladder of the nearest kind above it. */
|
|
374
|
+
ladderOf(kindName) {
|
|
375
|
+
const chain = this.ancestry(kindName);
|
|
376
|
+
for (let at = chain.length - 1; at >= 0; at -= 1) {
|
|
377
|
+
const ladder = chain[at]?.ladder;
|
|
378
|
+
if (ladder !== void 0) return ladder;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
/** This method gives the type of option of a kind: its own type, or the type of the nearest kind above it. */
|
|
382
|
+
optionOf(kindName) {
|
|
383
|
+
const chain = this.ancestry(kindName);
|
|
384
|
+
for (let at = chain.length - 1; at >= 0; at -= 1) {
|
|
385
|
+
const option = chain[at]?.option;
|
|
386
|
+
if (option !== void 0) return option;
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
/** This method gives each attribute of a kind: the attributes of its ancestors and their facets, then its own. */
|
|
390
|
+
effectiveShape(kindName) {
|
|
391
|
+
const shape = {};
|
|
392
|
+
for (const kind of this.ancestry(kindName)) {
|
|
393
|
+
for (const facetName of kind.facets ?? []) {
|
|
394
|
+
const facet = this.facets.get(facetName);
|
|
395
|
+
if (facet !== void 0) Object.assign(shape, facet.attributes);
|
|
396
|
+
}
|
|
397
|
+
Object.assign(shape, kind.attributes);
|
|
398
|
+
}
|
|
399
|
+
return shape;
|
|
400
|
+
}
|
|
401
|
+
/** This method gives the requirements of a kind: the requirements of its ancestors, then its own. */
|
|
402
|
+
effectiveRequirements(kindName) {
|
|
403
|
+
return this.ancestry(kindName).flatMap((kind) => kind.requirements ?? []);
|
|
404
|
+
}
|
|
405
|
+
/** This method gives the strict schema of the attributes of a kind, with the check of its requirements. */
|
|
406
|
+
effectiveSchema(kindName) {
|
|
407
|
+
const cached = this.schemaCache.get(kindName);
|
|
408
|
+
if (cached !== void 0) return cached;
|
|
409
|
+
const requirements = this.effectiveRequirements(kindName);
|
|
410
|
+
const object = z.strictObject(this.effectiveShape(kindName));
|
|
411
|
+
const schema = requirements.length === 0 ? object : object.superRefine((attrs, context) => {
|
|
412
|
+
for (const requirement of requirements) {
|
|
413
|
+
if (!Object.entries(requirement.when).every(([name, value]) => attrs[name] === value)) continue;
|
|
414
|
+
for (const name of requirement.then) if (attrs[name] === void 0) context.addIssue({
|
|
415
|
+
code: "custom",
|
|
416
|
+
path: [name],
|
|
417
|
+
message: `required: ${requirement.description}`
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
});
|
|
421
|
+
this.schemaCache.set(kindName, schema);
|
|
422
|
+
return schema;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* This method checks an entity and gives it with its parsed attributes. An entity with no scope gets the default
|
|
426
|
+
* scope of its kind.
|
|
427
|
+
*
|
|
428
|
+
* @throws RegistryError when the entity is not correct
|
|
429
|
+
*/
|
|
430
|
+
validateEntity(raw) {
|
|
431
|
+
const parsed = entitySchema.safeParse(raw);
|
|
432
|
+
if (!parsed.success) throw new RegistryError("invalid entity", zodIssues("entity", parsed.error));
|
|
433
|
+
const entity = parsed.data;
|
|
434
|
+
if (!this.kinds.has(entity.kind)) throw new RegistryError(`entity ${entity.id} has unknown kind ${entity.kind}`);
|
|
435
|
+
const attrs = this.effectiveSchema(entity.kind).safeParse(entity.attrs);
|
|
436
|
+
if (!attrs.success) throw new RegistryError(`invalid attrs for ${entity.id}`, zodIssues(entity.id, attrs.error));
|
|
437
|
+
const relation = this.relations.get(entity.kind);
|
|
438
|
+
if (relation !== void 0) {
|
|
439
|
+
const data = attrs.data;
|
|
440
|
+
const roles = Object.fromEntries(Object.keys(relation.roles ?? {}).filter((role) => data[role] !== void 0).map((role) => [role, data[role]]));
|
|
441
|
+
const id = this.relationIdOf({
|
|
442
|
+
type: entity.kind,
|
|
443
|
+
from: data.from,
|
|
444
|
+
to: data.to,
|
|
445
|
+
roles,
|
|
446
|
+
qualifiers: data
|
|
447
|
+
});
|
|
448
|
+
if (entity.id !== id) throw new RegistryError(`${entity.id}: a ${entity.kind} from ${data.from} to ${data.to} is ${id}`);
|
|
449
|
+
} else if (isRelationId(entity.id)) throw new RegistryError(`${entity.id}: rel. ids belong to relation instances, not a ${entity.kind}`);
|
|
450
|
+
const defaultScope = this.kinds.get(entity.kind)?.defaultScope;
|
|
451
|
+
const envelope = defaultScope !== void 0 && entity.envelope["scope"] === void 0 ? {
|
|
452
|
+
...entity.envelope,
|
|
453
|
+
scope: defaultScope
|
|
454
|
+
} : entity.envelope;
|
|
455
|
+
return {
|
|
456
|
+
...entity,
|
|
457
|
+
envelope,
|
|
458
|
+
attrs: attrs.data
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* This method gives the id of a relation from the key of its kind. A symmetric kind sorts its two ends, so the two
|
|
463
|
+
* orders give the same id. A key with only the two ends gives the id of `relationId`.
|
|
464
|
+
*
|
|
465
|
+
* @throws RegistryError when the relation kind is not known
|
|
466
|
+
*/
|
|
467
|
+
relationIdOf(edge) {
|
|
468
|
+
const relation = this.relations.get(edge.type);
|
|
469
|
+
if (relation === void 0) throw new RegistryError(`unknown relation kind: ${edge.type}`);
|
|
470
|
+
const symmetric = relation.symmetric === true;
|
|
471
|
+
const [a, b] = symmetric && edge.to < edge.from ? [edge.to, edge.from] : [edge.from, edge.to];
|
|
472
|
+
const parts = [];
|
|
473
|
+
for (const part of relation.key ?? ENDS_KEY) {
|
|
474
|
+
const value = part === "from" ? a : part === "to" ? b : relation.roles?.[part] !== void 0 ? edge.roles?.[part] : edge.qualifiers?.[part];
|
|
475
|
+
if (value !== void 0) parts.push([part, value]);
|
|
476
|
+
}
|
|
477
|
+
return parts.length === 2 && parts[0]?.[0] === "from" && parts[1]?.[0] === "to" ? relationId(edge.type, edge.from, edge.to, symmetric) : keyedRelationId(edge.type, parts);
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* This method checks an edge: its kind, the kinds of its ends and its role fillers, and its qualifiers. It gives
|
|
481
|
+
* the edge with its id.
|
|
482
|
+
*
|
|
483
|
+
* @param kindOf - This function gives the kind of an entity id, or `undefined` for an id with no entity.
|
|
484
|
+
* @throws RegistryError when the edge is not correct
|
|
485
|
+
*/
|
|
486
|
+
validateEdge(raw, kindOf) {
|
|
487
|
+
const parsed = edgeSchema.safeParse(raw);
|
|
488
|
+
if (!parsed.success) throw new RegistryError("invalid edge", zodIssues("edge", parsed.error));
|
|
489
|
+
const input = parsed.data;
|
|
490
|
+
const relation = this.relations.get(input.type);
|
|
491
|
+
if (relation === void 0) throw new RegistryError(`unknown relation kind: ${input.type}`);
|
|
492
|
+
const label = `${input.from} -${input.type}-> ${input.to}`;
|
|
493
|
+
if (relation.abstract === true) {
|
|
494
|
+
const narrower = [...this.relations.values()].filter((candidate) => candidate.parent === input.type).map((candidate) => candidate.name).sort();
|
|
495
|
+
throw new RegistryError(`${label}: ${input.type} is abstract, a family with no instances of its own: say which, ${narrower.join(" or ")}`);
|
|
496
|
+
}
|
|
497
|
+
const check = (part, endId, allowed) => {
|
|
498
|
+
const kind = kindOf(endId);
|
|
499
|
+
if (kind === void 0) throw new RegistryError(`${label}: ${part} entity ${endId} not found`);
|
|
500
|
+
if (allowed.length === 0) throw new RegistryError(`${label}: ${input.type} allows no ${part} kind yet: an add-on extends it`);
|
|
501
|
+
if (!allowed.some((ancestor) => this.isSubkindOf(kind, ancestor))) throw new RegistryError(`${label}: ${part} kind ${kind} not allowed (expected ${allowed.join("|")})`);
|
|
502
|
+
};
|
|
503
|
+
check("from", input.from, relation.from);
|
|
504
|
+
check("to", input.to, relation.to);
|
|
505
|
+
const roles = input.roles ?? {};
|
|
506
|
+
for (const [role, fillers] of Object.entries(roles)) {
|
|
507
|
+
const def = relation.roles?.[role];
|
|
508
|
+
if (def === void 0) throw new RegistryError(`${label}: relation kind ${input.type} has no role ${role}`);
|
|
509
|
+
const many = def.many === true;
|
|
510
|
+
if (many !== Array.isArray(fillers)) throw new RegistryError(`${label}: role ${role} takes ${many ? "a list of entities" : "one entity"}`);
|
|
511
|
+
const list = typeof fillers === "string" ? [fillers] : fillers;
|
|
512
|
+
if (list.length === 0 || new Set(list).size !== list.length) throw new RegistryError(`${label}: role ${role} lists each filler once, and at least one`);
|
|
513
|
+
for (const filler of list) check(`role ${role}`, filler, def.kinds);
|
|
514
|
+
}
|
|
515
|
+
let qualifiers = input.qualifiers;
|
|
516
|
+
if (relation.qualifiers !== void 0) {
|
|
517
|
+
const checked = z.strictObject(relation.qualifiers).safeParse(input.qualifiers);
|
|
518
|
+
if (!checked.success) throw new RegistryError(`invalid qualifiers for ${label}`, zodIssues(label, checked.error));
|
|
519
|
+
qualifiers = checked.data;
|
|
520
|
+
} else if (Object.keys(input.qualifiers).length > 0) throw new RegistryError(`${label}: relation kind ${input.type} declares no qualifiers`);
|
|
521
|
+
const hasRoles = Object.keys(roles).length > 0;
|
|
522
|
+
const id = this.relationIdOf({
|
|
523
|
+
...input,
|
|
524
|
+
roles,
|
|
525
|
+
qualifiers
|
|
526
|
+
});
|
|
527
|
+
if (input.id !== void 0 && input.id !== id) throw new RegistryError(`${label}: id ${input.id} is not this relation's (${id})`);
|
|
528
|
+
return {
|
|
529
|
+
id,
|
|
530
|
+
from: input.from,
|
|
531
|
+
type: input.type,
|
|
532
|
+
to: input.to,
|
|
533
|
+
...hasRoles ? { roles } : {},
|
|
534
|
+
qualifiers,
|
|
535
|
+
envelope: input.envelope
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* This method gives the registry as data: an entity for each kind and each facet. Each parent gives an edge
|
|
540
|
+
* `subkind-of`, and each facet of a kind gives an edge `has-facet`.
|
|
541
|
+
*/
|
|
542
|
+
toGraph() {
|
|
543
|
+
const entities = [];
|
|
544
|
+
const edges = [];
|
|
545
|
+
for (const facet of this.facets.values()) entities.push({
|
|
546
|
+
id: `ontology.facet.${facet.name}`,
|
|
547
|
+
kind: "facet",
|
|
548
|
+
attrs: {
|
|
549
|
+
name: facet.name,
|
|
550
|
+
description: facet.description
|
|
551
|
+
},
|
|
552
|
+
envelope: {}
|
|
553
|
+
});
|
|
554
|
+
for (const kind of this.kinds.values()) {
|
|
555
|
+
const relation = this.relations.get(kind.name);
|
|
556
|
+
entities.push({
|
|
557
|
+
id: `ontology.kind.${kind.name}`,
|
|
558
|
+
kind: "kind",
|
|
559
|
+
attrs: {
|
|
560
|
+
name: kind.name,
|
|
561
|
+
mode: kind.mode,
|
|
562
|
+
description: kind.description,
|
|
563
|
+
...relation !== void 0 ? {
|
|
564
|
+
from_kinds: [...relation.from],
|
|
565
|
+
to_kinds: [...relation.to],
|
|
566
|
+
...relation.symmetric === true ? { symmetric: true } : {},
|
|
567
|
+
...relation.transitive === true ? { transitive: true } : {},
|
|
568
|
+
...relation.roles !== void 0 ? { roles: Object.keys(relation.roles) } : {},
|
|
569
|
+
...relation.key !== void 0 ? { key: [...relation.key] } : {}
|
|
570
|
+
} : {}
|
|
571
|
+
},
|
|
572
|
+
envelope: {}
|
|
573
|
+
});
|
|
574
|
+
if (kind.parent !== null) edges.push({
|
|
575
|
+
from: `ontology.kind.${kind.name}`,
|
|
576
|
+
type: "subkind-of",
|
|
577
|
+
to: `ontology.kind.${kind.parent}`,
|
|
578
|
+
qualifiers: {},
|
|
579
|
+
envelope: {}
|
|
580
|
+
});
|
|
581
|
+
for (const facetName of kind.facets ?? []) edges.push({
|
|
582
|
+
from: `ontology.kind.${kind.name}`,
|
|
583
|
+
type: "has-facet",
|
|
584
|
+
to: `ontology.facet.${facetName}`,
|
|
585
|
+
qualifiers: {},
|
|
586
|
+
envelope: {}
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
return {
|
|
590
|
+
entities,
|
|
591
|
+
edges
|
|
592
|
+
};
|
|
593
|
+
}
|
|
594
|
+
};
|
|
595
|
+
// src/codegen/columns.ts
|
|
596
|
+
const defOf = (schema) => schema.def;
|
|
597
|
+
const WRAPPERS = /* @__PURE__ */ new Set([
|
|
598
|
+
"optional",
|
|
599
|
+
"nullable",
|
|
600
|
+
"default",
|
|
601
|
+
"readonly",
|
|
602
|
+
"nonoptional"
|
|
603
|
+
]);
|
|
604
|
+
const unwrap = (schema) => {
|
|
605
|
+
let def = defOf(schema);
|
|
606
|
+
while (WRAPPERS.has(def.type) && def.innerType !== void 0) def = defOf(def.innerType);
|
|
607
|
+
return def;
|
|
608
|
+
};
|
|
609
|
+
const scalar = (def) => {
|
|
610
|
+
switch (def.type) {
|
|
611
|
+
case "string":
|
|
612
|
+
case "enum":
|
|
613
|
+
case "literal": return "text";
|
|
614
|
+
case "number":
|
|
615
|
+
case "int": return "number";
|
|
616
|
+
case "boolean": return "boolean";
|
|
617
|
+
default: return "json";
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
/** This function gives the column shape of the schema of an attribute. */
|
|
621
|
+
const columnShape = (schema) => {
|
|
622
|
+
if (isQuantitySchema(schema)) return { kind: "quantity" };
|
|
623
|
+
const def = unwrap(schema);
|
|
624
|
+
if (def.type === "array" && def.element !== void 0) {
|
|
625
|
+
const element = scalar(unwrap(def.element));
|
|
626
|
+
return {
|
|
627
|
+
kind: "array",
|
|
628
|
+
element: element === "boolean" ? "json" : element
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
const kind = scalar(def);
|
|
632
|
+
return kind === "json" ? { kind: "json" } : { kind };
|
|
633
|
+
};
|
|
634
|
+
// src/codegen/header.ts
|
|
635
|
+
/** The default first line of each generated SQL file. */
|
|
636
|
+
const DEFAULT_HEADER = "-- Generated by @mark1russell7/ontology from the kinds of a registry. Do not edit by hand.";
|
|
637
|
+
/** This function gives the header line of a generated SQL file, with its line end. */
|
|
638
|
+
const headerOf = (options) => `${options?.header ?? "-- Generated by @mark1russell7/ontology from the kinds of a registry. Do not edit by hand."}\n`;
|
|
639
|
+
// src/codegen/duckdb.ts
|
|
640
|
+
const BASE_TABLES = `CREATE TABLE IF NOT EXISTS entities (
|
|
641
|
+
id VARCHAR PRIMARY KEY,
|
|
642
|
+
kind VARCHAR NOT NULL,
|
|
643
|
+
attrs JSON NOT NULL DEFAULT '{}',
|
|
644
|
+
envelope JSON NOT NULL DEFAULT '{}'
|
|
645
|
+
);
|
|
646
|
+
|
|
647
|
+
CREATE TABLE IF NOT EXISTS edges (
|
|
648
|
+
id VARCHAR NOT NULL,
|
|
649
|
+
from_id VARCHAR NOT NULL,
|
|
650
|
+
type VARCHAR NOT NULL,
|
|
651
|
+
to_id VARCHAR NOT NULL,
|
|
652
|
+
roles JSON NOT NULL DEFAULT '{}',
|
|
653
|
+
qualifiers JSON NOT NULL DEFAULT '{}',
|
|
654
|
+
envelope JSON NOT NULL DEFAULT '{}',
|
|
655
|
+
inverse BOOLEAN NOT NULL DEFAULT FALSE,
|
|
656
|
+
PRIMARY KEY (id, from_id)
|
|
657
|
+
);
|
|
658
|
+
|
|
659
|
+
CREATE INDEX IF NOT EXISTS idx_entities_kind ON entities (kind);
|
|
660
|
+
CREATE INDEX IF NOT EXISTS idx_edges_from ON edges (from_id);
|
|
661
|
+
CREATE INDEX IF NOT EXISTS idx_edges_to ON edges (to_id);
|
|
662
|
+
CREATE INDEX IF NOT EXISTS idx_edges_type ON edges (type);
|
|
663
|
+
`;
|
|
664
|
+
const identifier = (name) => name.replace(/-/g, "_");
|
|
665
|
+
const column = (key) => `"${identifier(key)}"`;
|
|
666
|
+
const attrColumn = (key, shape) => {
|
|
667
|
+
switch (shape.kind) {
|
|
668
|
+
case "text": return `attrs->>'${key}' AS ${column(key)}`;
|
|
669
|
+
case "number": return `CAST(attrs->>'${key}' AS DOUBLE) AS ${column(key)}`;
|
|
670
|
+
case "boolean": return `CAST(attrs->>'${key}' AS BOOLEAN) AS ${column(key)}`;
|
|
671
|
+
case "array":
|
|
672
|
+
if (shape.element === "text") return `CAST(attrs->'${key}' AS VARCHAR[]) AS ${column(key)}`;
|
|
673
|
+
if (shape.element === "number") return `CAST(attrs->'${key}' AS DOUBLE[]) AS ${column(key)}`;
|
|
674
|
+
return `attrs->'${key}' AS ${column(key)}`;
|
|
675
|
+
case "json": return `attrs->'${key}' AS ${column(key)}`;
|
|
676
|
+
case "quantity": return `TRY_CAST(attrs->'${key}'->>'value' AS DOUBLE) AS ${column(key)},\n attrs->'${key}'->>'unit' AS ${column(`${key}_unit`)}`;
|
|
677
|
+
}
|
|
678
|
+
};
|
|
679
|
+
/** This function gives the view columns of an attribute. A quantity has two columns. */
|
|
680
|
+
const columnNames = (key, shape) => shape.kind === "quantity" ? [key, `${key}_unit`] : [key];
|
|
681
|
+
const ENVELOPE_COLUMNS = [
|
|
682
|
+
"envelope->>'scope' AS envelope_scope",
|
|
683
|
+
"envelope->>'valid_from' AS envelope_valid_from",
|
|
684
|
+
"envelope->>'valid_to' AS envelope_valid_to",
|
|
685
|
+
"envelope->>'observed_at' AS envelope_observed_at"
|
|
686
|
+
];
|
|
687
|
+
const RESERVED_COLUMNS = /* @__PURE__ */ new Set([
|
|
688
|
+
"id",
|
|
689
|
+
"kind",
|
|
690
|
+
...ENVELOPE_COLUMNS.map((line) => line.slice(line.lastIndexOf(" AS ") + 4))
|
|
691
|
+
]);
|
|
692
|
+
/**
|
|
693
|
+
* This function gives the DuckDB tables of a store of entities and edges, and one view for each kind. The view of a
|
|
694
|
+
* kind has a column for each attribute, and it shows the entities of the kind and of each of its subkinds.
|
|
695
|
+
*
|
|
696
|
+
* @throws RegistryError when an attribute has the name of a fixed column, or two attributes give the same column
|
|
697
|
+
*/
|
|
698
|
+
const generateDuckDbDdl = (registry, options) => {
|
|
699
|
+
const sections = [headerOf(options), BASE_TABLES];
|
|
700
|
+
for (const kind of registry.kinds.values()) {
|
|
701
|
+
const kindList = [...registry.subkindClosure(kind.name)].sort().map((name) => `'${name}'`).join(", ");
|
|
702
|
+
const columns = ["id", "kind"];
|
|
703
|
+
const taken = /* @__PURE__ */ new Set();
|
|
704
|
+
for (const [key, schema] of Object.entries(registry.effectiveShape(kind.name))) {
|
|
705
|
+
if (RESERVED_COLUMNS.has(key)) throw new RegistryError(`kind ${kind.name}: attribute ${key} has the name of a fixed view column (id, kind or an envelope column)`);
|
|
706
|
+
const shape = columnShape(schema);
|
|
707
|
+
for (const name of columnNames(key, shape)) {
|
|
708
|
+
if (taken.has(identifier(name))) throw new RegistryError(`kind ${kind.name} has two view columns named ${identifier(name)}: the unit column of a quantity is <attribute>_unit`);
|
|
709
|
+
taken.add(identifier(name));
|
|
710
|
+
}
|
|
711
|
+
columns.push(attrColumn(key, shape));
|
|
712
|
+
}
|
|
713
|
+
columns.push(...ENVELOPE_COLUMNS);
|
|
714
|
+
sections.push(`CREATE OR REPLACE VIEW v_${identifier(kind.name)} AS\nSELECT\n ${columns.join(",\n ")}\nFROM entities\nWHERE kind IN (${kindList});\n`);
|
|
715
|
+
}
|
|
716
|
+
return sections.join("\n");
|
|
717
|
+
};
|
|
718
|
+
// src/codegen/sqlite.ts
|
|
719
|
+
/**
|
|
720
|
+
* This function gives the SQLite tables of a store of entities and edges. The tables are the same for each
|
|
721
|
+
* registry: a kind is a value of the column `kind`, and the attributes are JSON.
|
|
722
|
+
*/
|
|
723
|
+
const generateSqliteDdl = (_registry, options) => `${headerOf(options)}
|
|
724
|
+
CREATE TABLE IF NOT EXISTS entities (
|
|
725
|
+
id TEXT PRIMARY KEY,
|
|
726
|
+
kind TEXT NOT NULL,
|
|
727
|
+
attrs TEXT NOT NULL DEFAULT '{}',
|
|
728
|
+
envelope TEXT NOT NULL DEFAULT '{}'
|
|
729
|
+
);
|
|
730
|
+
|
|
731
|
+
CREATE TABLE IF NOT EXISTS edges (
|
|
732
|
+
id TEXT NOT NULL,
|
|
733
|
+
from_id TEXT NOT NULL,
|
|
734
|
+
type TEXT NOT NULL,
|
|
735
|
+
to_id TEXT NOT NULL,
|
|
736
|
+
roles TEXT NOT NULL DEFAULT '{}',
|
|
737
|
+
qualifiers TEXT NOT NULL DEFAULT '{}',
|
|
738
|
+
envelope TEXT NOT NULL DEFAULT '{}',
|
|
739
|
+
inverse INTEGER NOT NULL DEFAULT 0,
|
|
740
|
+
PRIMARY KEY (id, from_id)
|
|
741
|
+
);
|
|
742
|
+
|
|
743
|
+
CREATE INDEX IF NOT EXISTS idx_entities_kind ON entities (kind);
|
|
744
|
+
CREATE INDEX IF NOT EXISTS idx_edges_from ON edges (from_id);
|
|
745
|
+
CREATE INDEX IF NOT EXISTS idx_edges_to ON edges (to_id);
|
|
746
|
+
CREATE INDEX IF NOT EXISTS idx_edges_type ON edges (type);
|
|
747
|
+
`;
|
|
748
|
+
// src/codegen/jsonschema.ts
|
|
749
|
+
/** This function gives the JSON Schema of the requirements of a kind: an `if` and a `then` for each. */
|
|
750
|
+
const requirementsJson = (requirements) => requirements.length === 0 ? {} : { allOf: requirements.map((requirement) => ({
|
|
751
|
+
description: requirement.description,
|
|
752
|
+
if: {
|
|
753
|
+
properties: Object.fromEntries(Object.entries(requirement.when).map(([name, value]) => [name, { const: value }])),
|
|
754
|
+
required: Object.keys(requirement.when)
|
|
755
|
+
},
|
|
756
|
+
then: { required: [...requirement.then] }
|
|
757
|
+
})) };
|
|
758
|
+
/** This function gives one kind as data. The schema includes the attributes of the facets of the kind. */
|
|
759
|
+
const kindJson = (registry, kind) => {
|
|
760
|
+
const facets = kind.facets ?? [];
|
|
761
|
+
const shape = Object.assign({}, ...facets.map((name) => registry.facets.get(name)?.attributes ?? {}), kind.attributes);
|
|
762
|
+
return {
|
|
763
|
+
name: kind.name,
|
|
764
|
+
parent: kind.parent,
|
|
765
|
+
mode: kind.mode,
|
|
766
|
+
description: kind.description,
|
|
767
|
+
attributes: {
|
|
768
|
+
...z.toJSONSchema(z.strictObject(shape)),
|
|
769
|
+
...requirementsJson(kind.requirements ?? [])
|
|
770
|
+
},
|
|
771
|
+
...facets.length > 0 ? { facets: [...facets] } : {},
|
|
772
|
+
...kind.defaultScope !== void 0 ? { defaultScope: kind.defaultScope } : {},
|
|
773
|
+
...kind.staleAfterDays !== void 0 ? { staleAfterDays: kind.staleAfterDays } : {},
|
|
774
|
+
...kind.requirements !== void 0 && kind.requirements.length > 0 ? { requirements: [...kind.requirements] } : {}
|
|
775
|
+
};
|
|
776
|
+
};
|
|
777
|
+
/** This function gives one relation kind as data. */
|
|
778
|
+
const relationJson = (relation) => ({
|
|
779
|
+
name: relation.name,
|
|
780
|
+
...relation.parent !== void 0 ? { parent: relation.parent } : {},
|
|
781
|
+
description: relation.description,
|
|
782
|
+
from: [...relation.from],
|
|
783
|
+
to: [...relation.to],
|
|
784
|
+
...relation.qualifiers !== void 0 ? { qualifiers: z.toJSONSchema(z.strictObject(relation.qualifiers)) } : {},
|
|
785
|
+
...relation.symmetric !== void 0 ? { symmetric: relation.symmetric } : {},
|
|
786
|
+
...relation.transitive !== void 0 ? { transitive: relation.transitive } : {},
|
|
787
|
+
...relation.abstract === true ? { abstract: true } : {},
|
|
788
|
+
...relation.roles !== void 0 ? { roles: Object.fromEntries(Object.entries(relation.roles).map(([role, def]) => [role, {
|
|
789
|
+
description: def.description,
|
|
790
|
+
kinds: [...def.kinds],
|
|
791
|
+
...def.many === true ? { many: true } : {}
|
|
792
|
+
}])) } : {},
|
|
793
|
+
...relation.key !== void 0 ? { key: [...relation.key] } : {}
|
|
794
|
+
});
|
|
795
|
+
/** This function gives a registry as data: each kind and each relation kind. */
|
|
796
|
+
const registryJson = (registry) => ({
|
|
797
|
+
kinds: [...registry.kinds.values()].map((kind) => kindJson(registry, kind)),
|
|
798
|
+
relations: [...registry.relations.values()].map(relationJson)
|
|
799
|
+
});
|
|
800
|
+
/** This function gives the JSON Schemas of an entity, an edge, and the full attributes of each kind. */
|
|
801
|
+
const generateJsonSchemas = (registry) => ({
|
|
802
|
+
entity: z.toJSONSchema(entitySchema),
|
|
803
|
+
edge: z.toJSONSchema(edgeSchema),
|
|
804
|
+
kinds: Object.fromEntries([...registry.kinds.keys()].map((name) => [name, {
|
|
805
|
+
...z.toJSONSchema(z.strictObject(registry.effectiveShape(name))),
|
|
806
|
+
...requirementsJson(registry.effectiveRequirements(name))
|
|
807
|
+
}]))
|
|
808
|
+
});
|
|
809
|
+
// src/generate.ts
|
|
810
|
+
/** This function gives each generated file of a registry: the SQL of two stores, the registry and the JSON Schemas. */
|
|
811
|
+
const generateAll = (registry, options) => ({
|
|
812
|
+
"duckdb.sql": generateDuckDbDdl(registry, options),
|
|
813
|
+
"sqlite.sql": generateSqliteDdl(registry, options),
|
|
814
|
+
"registry.json": `${JSON.stringify(registryJson(registry), null, 2)}\n`,
|
|
815
|
+
"jsonschema.json": `${JSON.stringify(generateJsonSchemas(registry), null, 2)}\n`
|
|
816
|
+
});
|
|
817
|
+
export { visibleTo as A, isRelationId as C, relationId as D, nameOf as E, scopeRank as O, envelopeSchema as S, maxScope as T, SCOPES as _, relationJson as a, entityIdSchema as b, DEFAULT_HEADER as c, Registry as d, RegistryError as f, NAME_PATTERN as g, MODES as h, registryJson as i, scopeSchema as k, columnShape as l, ENTITY_ID_PATTERN as m, generateJsonSchemas as n, generateSqliteDdl as o, composeRegistryInput as p, kindJson as r, generateDuckDbDdl as s, generateAll as t, RELATION_ROOT as u, edgeRowSchema as v, keyedRelationId as w, entitySchema as x, edgeSchema as y };
|
|
818
|
+
|
|
819
|
+
//# sourceMappingURL=generate-Dv-t-uia.mjs.map
|