@crubal/engine 0.0.0-stage → 0.4.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.
Files changed (114) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +97 -2
  3. package/dist/bin/crubal.d.ts +2 -0
  4. package/dist/bin/crubal.js +103 -0
  5. package/dist/bin/crubal.js.map +1 -0
  6. package/dist/src/access.d.ts +149 -0
  7. package/dist/src/access.js +584 -0
  8. package/dist/src/access.js.map +1 -0
  9. package/dist/src/acts.d.ts +531 -0
  10. package/dist/src/acts.js +1466 -0
  11. package/dist/src/acts.js.map +1 -0
  12. package/dist/src/address.d.ts +29 -0
  13. package/dist/src/address.js +59 -0
  14. package/dist/src/address.js.map +1 -0
  15. package/dist/src/arrival.d.ts +55 -0
  16. package/dist/src/arrival.js +127 -0
  17. package/dist/src/arrival.js.map +1 -0
  18. package/dist/src/browser.d.ts +10 -0
  19. package/dist/src/browser.js +13 -0
  20. package/dist/src/browser.js.map +1 -0
  21. package/dist/src/bundle.d.ts +74 -0
  22. package/dist/src/bundle.js +1108 -0
  23. package/dist/src/bundle.js.map +1 -0
  24. package/dist/src/canonical.d.ts +6 -0
  25. package/dist/src/canonical.js +47 -0
  26. package/dist/src/canonical.js.map +1 -0
  27. package/dist/src/carriers.d.ts +7 -0
  28. package/dist/src/carriers.js +33 -0
  29. package/dist/src/carriers.js.map +1 -0
  30. package/dist/src/conditions.d.ts +28 -0
  31. package/dist/src/conditions.js +227 -0
  32. package/dist/src/conditions.js.map +1 -0
  33. package/dist/src/corpus.d.ts +8 -0
  34. package/dist/src/corpus.js +1207 -0
  35. package/dist/src/corpus.js.map +1 -0
  36. package/dist/src/defs.d.ts +174 -0
  37. package/dist/src/defs.js +690 -0
  38. package/dist/src/defs.js.map +1 -0
  39. package/dist/src/dictionary.d.ts +77 -0
  40. package/dist/src/dictionary.js +629 -0
  41. package/dist/src/dictionary.js.map +1 -0
  42. package/dist/src/exchange.d.ts +259 -0
  43. package/dist/src/exchange.js +1088 -0
  44. package/dist/src/exchange.js.map +1 -0
  45. package/dist/src/forms.d.ts +16 -0
  46. package/dist/src/forms.js +181 -0
  47. package/dist/src/forms.js.map +1 -0
  48. package/dist/src/index.d.ts +32 -0
  49. package/dist/src/index.js +34 -0
  50. package/dist/src/index.js.map +1 -0
  51. package/dist/src/lex.d.ts +21 -0
  52. package/dist/src/lex.js +142 -0
  53. package/dist/src/lex.js.map +1 -0
  54. package/dist/src/lifecycle.d.ts +92 -0
  55. package/dist/src/lifecycle.js +451 -0
  56. package/dist/src/lifecycle.js.map +1 -0
  57. package/dist/src/log.d.ts +91 -0
  58. package/dist/src/log.js +629 -0
  59. package/dist/src/log.js.map +1 -0
  60. package/dist/src/migrate.d.ts +129 -0
  61. package/dist/src/migrate.js +415 -0
  62. package/dist/src/migrate.js.map +1 -0
  63. package/dist/src/model.d.ts +81 -0
  64. package/dist/src/model.js +188 -0
  65. package/dist/src/model.js.map +1 -0
  66. package/dist/src/packages.d.ts +372 -0
  67. package/dist/src/packages.js +1158 -0
  68. package/dist/src/packages.js.map +1 -0
  69. package/dist/src/print-text.d.ts +7 -0
  70. package/dist/src/print-text.js +223 -0
  71. package/dist/src/print-text.js.map +1 -0
  72. package/dist/src/publish.d.ts +27 -0
  73. package/dist/src/publish.js +279 -0
  74. package/dist/src/publish.js.map +1 -0
  75. package/dist/src/read-text.d.ts +10 -0
  76. package/dist/src/read-text.js +400 -0
  77. package/dist/src/read-text.js.map +1 -0
  78. package/dist/src/records.d.ts +32 -0
  79. package/dist/src/records.js +104 -0
  80. package/dist/src/records.js.map +1 -0
  81. package/dist/src/review.d.ts +22 -0
  82. package/dist/src/review.js +198 -0
  83. package/dist/src/review.js.map +1 -0
  84. package/dist/src/rules.d.ts +101 -0
  85. package/dist/src/rules.js +670 -0
  86. package/dist/src/rules.js.map +1 -0
  87. package/dist/src/schedule.d.ts +24 -0
  88. package/dist/src/schedule.js +126 -0
  89. package/dist/src/schedule.js.map +1 -0
  90. package/dist/src/std-packages.d.ts +9 -0
  91. package/dist/src/std-packages.js +268 -0
  92. package/dist/src/std-packages.js.map +1 -0
  93. package/dist/src/store.d.ts +191 -0
  94. package/dist/src/store.js +671 -0
  95. package/dist/src/store.js.map +1 -0
  96. package/dist/src/surface.d.ts +47 -0
  97. package/dist/src/surface.js +92 -0
  98. package/dist/src/surface.js.map +1 -0
  99. package/dist/src/tree.d.ts +35 -0
  100. package/dist/src/tree.js +159 -0
  101. package/dist/src/tree.js.map +1 -0
  102. package/dist/src/units-table.d.ts +1 -0
  103. package/dist/src/units-table.js +200 -0
  104. package/dist/src/units-table.js.map +1 -0
  105. package/dist/src/units.d.ts +42 -0
  106. package/dist/src/units.js +98 -0
  107. package/dist/src/units.js.map +1 -0
  108. package/dist/src/versions.d.ts +10 -0
  109. package/dist/src/versions.js +27 -0
  110. package/dist/src/versions.js.map +1 -0
  111. package/dist/src/views.d.ts +372 -0
  112. package/dist/src/views.js +1170 -0
  113. package/dist/src/views.js.map +1 -0
  114. package/package.json +60 -4
@@ -0,0 +1,629 @@
1
+ // dictionary.ts: the Dictionary level (spec chapters 4 and 5). Definitions as JSON (4.6), the publish
2
+ // checks on definitions and classes (4.7, 5.10), class resolution by meet (5.4), alias folding (4.3), and
3
+ // checking each value against its facet and the classes its record wears (4.9, 5.3, 5.5, 5.6).
4
+ import { evaluate, parseCondition } from "./conditions.js";
5
+ import { definitionSortOf } from "./defs.js";
6
+ import { itemText } from "./print-text.js";
7
+ import { readUnder } from "./read-text.js";
8
+ import { CrubalError } from "./tree.js";
9
+ import { convert, knownUnit, unitOf } from "./units.js";
10
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
11
+ /** A fold key (4.3): NFC, case-folded, trimmed, inner white space made one space. */
12
+ export function foldKey(s) {
13
+ return s.normalize("NFC").toLowerCase().trim().replace(/\s+/g, " ");
14
+ }
15
+ // ─── Definitions as JSON (4.6) ────────────────────────────────────────────────
16
+ export function facetJson(f) {
17
+ const o = { facet: f.key, type: f.type };
18
+ const put = (k, v, skip) => {
19
+ if (v === undefined || v === skip)
20
+ return;
21
+ if (Array.isArray(v) && v.length === 0)
22
+ return;
23
+ o[k] = v;
24
+ };
25
+ put("label", f.label);
26
+ put("ask", f.ask);
27
+ put("describe", f.describe);
28
+ put("pick", f.pick, "1");
29
+ put("ordered", f.ordered || undefined);
30
+ put("state", f.state, "active");
31
+ put("qualifiers", f.qualifiers);
32
+ put("aliases", f.aliases);
33
+ put("same-as", f.sameAs);
34
+ put("agree-by", f.agreeBy);
35
+ put("length", f.length === undefined ? undefined : String(f.length));
36
+ put("unit", f.unit);
37
+ put("accepts", f.accepts);
38
+ if (f.range)
39
+ o.range = { ...f.range };
40
+ put("places", f.places === undefined ? undefined : String(f.places));
41
+ put("precision", f.precision, "any");
42
+ if (f.words)
43
+ o.words = [...f.words];
44
+ if (f.values)
45
+ o.values = f.values.map((v) => (v.aliases.length ? { value: v.value, aliases: [...v.aliases] } : { value: v.value }));
46
+ put("open", f.open || undefined);
47
+ for (const k of ["fixed", "ranked", "scored", "required", "na", "unique", "transitions"])
48
+ put(k, f[k] || undefined);
49
+ put("to", f.to);
50
+ if (f.children)
51
+ o.facets = [...f.children.values()].map(facetJson);
52
+ put("identity", f.identity);
53
+ put("when", f.when);
54
+ put("combine", f.combine);
55
+ put("version", f.version);
56
+ for (const [k, v] of Object.entries(f.extra))
57
+ o[k] = v;
58
+ return o;
59
+ }
60
+ function checkFacet(f) {
61
+ const line = f.line;
62
+ if (f.type === "choice" && !f.values?.length)
63
+ throw new CrubalError(`the choice facet ${f.key} has no values`, line);
64
+ if (f.type === "compound" && !f.children?.size)
65
+ throw new CrubalError(`the compound facet ${f.key} has no children`, line);
66
+ if (f.open && f.fixed)
67
+ throw new CrubalError(`the list of ${f.key} is both open and fixed`, line);
68
+ if ((f.ranked || f.scored || f.fixed || f.open) && f.type !== "choice") {
69
+ throw new CrubalError(`${f.key}: ranked, scored, fixed and open lists are for choice facets`, line);
70
+ }
71
+ if (f.ordered && !f.many)
72
+ throw new CrubalError(`${f.key} is ordered but holds one value`, line);
73
+ if (f.accepts.length && !f.unit)
74
+ throw new CrubalError(`${f.key} accepts other units but has no unit`, line);
75
+ // 4.7 (6): a unit is a spelling from the units table, `currency`, or an ISO 4217 code.
76
+ for (const u of [...(f.unit ? [f.unit] : []), ...f.accepts])
77
+ if (!knownUnit(u))
78
+ throw new CrubalError(`${f.key}: ${u} isn't a unit the units table knows`, line);
79
+ if (f.range && Number(f.range.min) > Number(f.range.max))
80
+ throw new CrubalError(`${f.key}'s range runs backwards`, line);
81
+ if (f.identity) {
82
+ const child = f.children?.get(f.identity);
83
+ if (!child)
84
+ throw new CrubalError(`the identity child ${f.identity} of ${f.key} isn't one of its children`, line);
85
+ if (child.type !== "link")
86
+ throw new CrubalError(`the identity child ${f.identity} of ${f.key} is not a link`, line);
87
+ }
88
+ const seen = new Map();
89
+ for (const v of f.values ?? []) {
90
+ for (const spelling of [v.value, ...v.aliases]) {
91
+ const k = foldKey(spelling);
92
+ const owner = seen.get(k);
93
+ if (owner !== undefined && owner !== v.value) {
94
+ throw new CrubalError(`${f.key}: the spelling ${spelling} folds to the same as ${owner}`, line);
95
+ }
96
+ seen.set(k, v.value);
97
+ }
98
+ }
99
+ for (const c of f.children?.values() ?? []) {
100
+ if (["row", "origin", "via", "owner"].includes(c.key))
101
+ throw new CrubalError(`${f.key} has a child named ${c.key}, which is reserved`, line);
102
+ checkFacet(c);
103
+ }
104
+ }
105
+ /** Run every publish check on a dictionary. Throws the first error; returns warnings. */
106
+ export function checkPackage(dict) {
107
+ const warnings = [];
108
+ // An identify key names a record, so it must be a facet and unique (11.2).
109
+ for (const [level, ks] of dict.identify) {
110
+ for (const k of ks) {
111
+ const f = dict.facets.get(k);
112
+ if (!f)
113
+ throw new CrubalError(`identify names ${k} at ${level}, which isn't a facet`);
114
+ if (!f.unique)
115
+ throw new CrubalError(`${k} is an identify key at ${level}, so it must be unique`, f.line);
116
+ }
117
+ }
118
+ const keys = new Map();
119
+ for (const f of dict.facets.values()) {
120
+ if (f.key.startsWith("crubal:"))
121
+ continue;
122
+ checkFacet(f);
123
+ for (const spelling of [f.key, ...f.aliases]) {
124
+ const k = foldKey(spelling);
125
+ const owner = keys.get(k);
126
+ if (owner !== undefined && owner !== f.key) {
127
+ const what = spelling === f.key ? `the key ${f.key}` : `the alias ${spelling} of ${f.key}`;
128
+ throw new CrubalError(`${what} folds to ${owner === k ? "the key" : "an alias"} of ${owner}`, f.line);
129
+ }
130
+ keys.set(k, f.key);
131
+ }
132
+ }
133
+ for (const c of dict.classes.values()) {
134
+ for (const l of c.lines)
135
+ checkClassLine(c, l, dict);
136
+ for (const slot of c.parts) {
137
+ if (!dict.classes.has(slot.wears))
138
+ throw new CrubalError(`the part slot ${slot.slot} wears ${slot.wears}, which isn't a class`, slot.line);
139
+ }
140
+ }
141
+ // 5.10 (4): a level prefix names a level of every kind in `for` (every kind, when `for` is absent).
142
+ const kindsAll = [...new Set(dict.levels.values())];
143
+ const levelsOf = (kind) => [...dict.levels].filter(([, k]) => k === kind).map(([l]) => l);
144
+ for (const c of dict.classes.values()) {
145
+ for (const l of c.lines) {
146
+ if (!l.level)
147
+ continue;
148
+ for (const kind of c.for.length ? c.for : kindsAll)
149
+ if (!levelsOf(kind).includes(l.level))
150
+ throw new CrubalError(`${c.name}: ${l.level}:: isn't a level of ${kind}`, l.line);
151
+ }
152
+ }
153
+ for (const c of dict.classes.values()) {
154
+ findCycle(c.name, dict, []);
155
+ resolve(dict, [c.name], c.line);
156
+ warnings.push(...redundantLines(c, dict));
157
+ }
158
+ return warnings;
159
+ }
160
+ function checkClassLine(c, l, dict) {
161
+ const f = dict.facets.get(l.facet);
162
+ if (!f)
163
+ throw new CrubalError(`the class line ${l.text} names a facet that isn't defined`, l.line);
164
+ if (f.state === "candidate")
165
+ throw new CrubalError(`${f.key} is a candidate; a class line can only name an active facet`, l.line);
166
+ if (f.state === "retired")
167
+ throw new CrubalError(`${f.key} is retired; a class line can only name an active facet`, l.line);
168
+ const type = l.type;
169
+ if (type && type !== f.type)
170
+ throw new CrubalError(`the class line ${l.text} marks ${f.key} as ${type}, but it is ${f.type}`, l.line);
171
+ if (l.values) {
172
+ const real = new Set((f.values ?? []).map((v) => v.value));
173
+ const extra = l.values.filter((v) => !real.has(v));
174
+ if (extra.length)
175
+ throw new CrubalError(`the class line ${l.text} widens ${f.key}: ${extra.join(", ")} is not one of its values`, l.line);
176
+ }
177
+ if (l.length !== undefined && f.length !== undefined && l.length > f.length)
178
+ throw new CrubalError(`the class line ${l.text} widens ${f.key}'s length`, l.line);
179
+ if (l.pick && f.pick !== "any" && (l.pick === "any" || Number(l.pick) > Number(f.pick)))
180
+ throw new CrubalError(`the class line ${l.text} widens ${f.key}'s pick`, l.line);
181
+ if (l.range && f.range && (Number(l.range.min) < Number(f.range.min) || Number(l.range.max) > Number(f.range.max))) {
182
+ throw new CrubalError(`the class line ${l.text} widens ${f.key}'s range`, l.line);
183
+ }
184
+ if (l.when)
185
+ parseCondition(l.when, l.line);
186
+ if (l.frame && f.type !== "image")
187
+ throw new CrubalError(`the class line ${l.text} gives ${f.key} a frame, but it isn't an image`, l.line);
188
+ void c;
189
+ }
190
+ function findCycle(name, dict, path) {
191
+ if (path.includes(name)) {
192
+ const loop = path.slice(path.indexOf(name));
193
+ const first = dict.classes.get(loop[0]);
194
+ throw new CrubalError(`the classes ${loop.join(" and ")} use each other`, first?.line);
195
+ }
196
+ const c = dict.classes.get(name);
197
+ if (!c)
198
+ return;
199
+ for (const u of c.uses) {
200
+ if (!dict.classes.has(u))
201
+ throw new CrubalError(`${name} uses ${u}, which isn't a class`, c.line);
202
+ findCycle(u, dict, [...path, name]);
203
+ }
204
+ }
205
+ function order(dict, names, seen = new Set()) {
206
+ const out = [];
207
+ for (const n of names) {
208
+ if (seen.has(n))
209
+ continue;
210
+ const c = dict.classes.get(n);
211
+ if (!c)
212
+ continue;
213
+ seen.add(n);
214
+ out.push(...order(dict, c.uses, seen), c);
215
+ }
216
+ return out;
217
+ }
218
+ /** Resolve the meet of classes (a class with its uses, or everything a record wears). */
219
+ export function resolve(dict, names, line) {
220
+ const lines = new Map();
221
+ for (const c of order(dict, names)) {
222
+ for (const l of c.lines) {
223
+ const f = dict.facets.get(l.facet);
224
+ let r = lines.get(l.facet);
225
+ if (!r) {
226
+ r = { facet: l.facet, levels: [], from: [] };
227
+ if (l.section)
228
+ r.section = l.section;
229
+ lines.set(l.facet, r);
230
+ }
231
+ r.from.push({ cls: c.name, line: l });
232
+ if (l.required)
233
+ r.required = true;
234
+ if (l.level && !r.levels.includes(l.level))
235
+ r.levels.push(l.level);
236
+ if (l.when)
237
+ r.when = r.when ? `(${r.when}) and (${l.when})` : l.when;
238
+ if (l.values) {
239
+ const base = r.values ?? (f?.values ?? []).map((v) => v.value);
240
+ const next = base.filter((v) => l.values?.includes(v));
241
+ if (!next.length) {
242
+ const others = r.from.filter((x) => x.line.values && x.cls !== c.name).map((x) => x.cls);
243
+ throw new CrubalError(`${names.join(", ")} allows no value of ${l.facet}: ${[...new Set([...others, c.name])].join(" and ")} have nothing in common`, line ?? l.line);
244
+ }
245
+ r.values = next;
246
+ }
247
+ if (l.length !== undefined)
248
+ r.length = Math.min(r.length ?? Number.POSITIVE_INFINITY, l.length);
249
+ if (l.pick)
250
+ r.pick = r.pick && r.pick !== "any" && (l.pick === "any" || Number(r.pick) < Number(l.pick)) ? r.pick : l.pick;
251
+ if (l.range) {
252
+ const min = r.range ? String(Math.max(Number(r.range.min), Number(l.range.min))) : l.range.min;
253
+ const max = r.range ? String(Math.min(Number(r.range.max), Number(l.range.max))) : l.range.max;
254
+ r.range = { min, max };
255
+ }
256
+ }
257
+ }
258
+ return [...lines.values()];
259
+ }
260
+ /** A resolved class as JSON, as the corpus states it. */
261
+ export function resolvedJson(lines) {
262
+ return lines.map((r) => {
263
+ const o = { facet: r.facet };
264
+ if (r.required)
265
+ o.required = true;
266
+ if (r.values)
267
+ o.values = r.values;
268
+ if (r.length !== undefined)
269
+ o.length = String(r.length);
270
+ if (r.pick)
271
+ o.pick = r.pick;
272
+ if (r.range)
273
+ o.range = r.range;
274
+ if (r.levels.length === 1)
275
+ o.level = r.levels[0];
276
+ else if (r.levels.length > 1)
277
+ o.levels = r.levels;
278
+ if (r.when)
279
+ o.when = r.when;
280
+ return o;
281
+ });
282
+ }
283
+ function redundantLines(c, dict) {
284
+ const inherited = new Map(resolve(dict, c.uses).map((r) => [r.facet, r]));
285
+ const out = [];
286
+ for (const l of c.lines) {
287
+ if (!inherited.has(l.facet))
288
+ continue;
289
+ const narrows = l.required || l.values || l.length !== undefined || l.pick || l.range || l.level || l.when;
290
+ if (!narrows)
291
+ out.push({ line: l.line, message: `${c.name} restates ${l.facet}, which a used class already asks for` });
292
+ }
293
+ return out;
294
+ }
295
+ // ─── Folding (4.3) ───────────────────────────────────────────────────────────
296
+ function keyIndex(dict) {
297
+ const idx = new Map();
298
+ for (const f of dict.facets.values()) {
299
+ for (const s of [f.key, ...f.aliases])
300
+ idx.set(foldKey(s), f.key);
301
+ }
302
+ return idx;
303
+ }
304
+ function foldChoice(f, v) {
305
+ if (typeof v === "string" && f.values) {
306
+ const k = foldKey(v);
307
+ for (const cv of f.values)
308
+ if ([cv.value, ...cv.aliases].some((s) => foldKey(s) === k))
309
+ return cv.value;
310
+ return v;
311
+ }
312
+ if (isObj(v) && "$value" in v)
313
+ return { ...v, $value: foldChoice(f, v.$value) };
314
+ return v;
315
+ }
316
+ function foldQuantity(f, v, units) {
317
+ if (!isObj(v) || !("$qty" in v) || !f.unit)
318
+ return v;
319
+ const from = unitOf(String(v.unit), units) ?? String(v.unit);
320
+ if (from === f.unit)
321
+ return from === v.unit ? v : { $qty: v.$qty, unit: from };
322
+ if (!f.accepts.includes(from) && !f.accepts.includes(String(v.unit)))
323
+ return v;
324
+ const amount = convert(String(v.$qty), from, f.unit, f.places, units);
325
+ return amount === null ? v : { $qty: amount, unit: f.unit };
326
+ }
327
+ /** A color's hex code in its canonical uppercase (1.4.9a): a value as given, its hex folded. */
328
+ function foldColor(v) {
329
+ if (typeof v === "string" && HEX.test(v))
330
+ return v.toUpperCase();
331
+ if (isObj(v) && "$color" in v && typeof v.hex === "string" && HEX.test(v.hex))
332
+ return { ...v, hex: v.hex.toUpperCase() };
333
+ if (isObj(v) && "$value" in v)
334
+ return { ...v, $value: foldColor(v.$value) };
335
+ return v;
336
+ }
337
+ export function foldValue(f, v, dict) {
338
+ if (Array.isArray(v))
339
+ return v.map((x) => foldValue(f, x, dict));
340
+ if (f.type === "choice")
341
+ return foldChoice(f, v);
342
+ if (f.type === "number")
343
+ return foldQuantity(f, v, dict.units);
344
+ if (f.type === "color")
345
+ return foldColor(v);
346
+ if (f.type === "compound" && isObj(v))
347
+ return foldFields(v, f.children ?? new Map(), dict);
348
+ return v;
349
+ }
350
+ function foldFields(obj, within, dict) {
351
+ const idx = within ? new Map([...within.keys()].map((k) => [foldKey(k), k])) : keyIndex(dict);
352
+ const out = {};
353
+ for (const [k, v] of Object.entries(obj)) {
354
+ const lookup = within ?? dict.facets;
355
+ let key = k;
356
+ let value = v;
357
+ let f = lookup.get(k);
358
+ if (!f) {
359
+ const real = idx.get(foldKey(k));
360
+ const rf = real ? lookup.get(real) : undefined;
361
+ if (real && rf && typeof v === "string") {
362
+ key = real;
363
+ f = rf;
364
+ value = readUnder(rf, v, dict) ?? v;
365
+ }
366
+ }
367
+ out[key] = f ? foldValue(f, value, dict) : value;
368
+ }
369
+ return out;
370
+ }
371
+ /** Fold a record: key aliases, value aliases and accepted units become real names (chapter 4.3). */
372
+ export function foldRecord(r, dict) {
373
+ const out = { ...r, values: foldFields(r.values, null, dict) };
374
+ if (r.parts) {
375
+ out.parts = r.parts.map((p) => (isObj(p) && isObj(p.values) ? { ...p, values: foldFields(p.values, null, dict) } : p));
376
+ }
377
+ return out;
378
+ }
379
+ const NUMBER = /^-?(0|[1-9]\d*)(\.\d+)?$/;
380
+ const DATE = /^(\d{4})(?:-(\d{2})(?:-(\d{2})(?:T(\d{2})(?::(\d{2})(?::(\d{2}))?)?(Z|[+-]\d{2}:\d{2})?)?)?)?$/;
381
+ const TIME = /^(\d{2}):(\d{2})(?::(\d{2}))?$/;
382
+ const RANK = { year: 0, month: 1, day: 2, hour: 3, minute: 4, second: 5 };
383
+ /** A date's precision and whether it is well formed (1.4.5): real calendar parts and clock parts. */
384
+ export function dateParts(d) {
385
+ const m = d.match(DATE);
386
+ if (!m)
387
+ return null;
388
+ const [, , mo, dd, hh, mi, ss, off] = m;
389
+ if (mo && (Number(mo) < 1 || Number(mo) > 12))
390
+ return null;
391
+ if (dd && (Number(dd) < 1 || Number(dd) > 31))
392
+ return null;
393
+ if (hh && Number(hh) > 23)
394
+ return null;
395
+ if (mi && Number(mi) > 59)
396
+ return null;
397
+ if (ss && Number(ss) > 59)
398
+ return null;
399
+ const precision = ss ? "second" : mi ? "minute" : hh ? "hour" : dd ? "day" : mo ? "month" : "year";
400
+ return { precision, offset: off ?? null };
401
+ }
402
+ function core(v) {
403
+ return isObj(v) && "$value" in v ? v.$value : v;
404
+ }
405
+ /** The name a definition link holds, when it is of the sort given: `def:facet:title` → `title`. Pure. */
406
+ export function definitionName(link, sort) {
407
+ const prefix = `def:${sort}:`;
408
+ const name = link.startsWith(prefix) ? link.slice(prefix.length) : "";
409
+ return name ? name : undefined;
410
+ }
411
+ /**
412
+ * The definition a link names, as the dictionary holds it now (4.2.2): a facet through its aliases, so a renamed
413
+ * facet keeps its links; a kind or a class by name. Other sorts (utility, event, package, lane, form, view) live
414
+ * outside the dictionary and are resolved by the host; for them this answers the name unchanged.
415
+ */
416
+ export function resolveDefinition(dict, link, sort) {
417
+ const name = definitionName(link, sort);
418
+ if (!name)
419
+ return undefined;
420
+ if (sort === "facet") {
421
+ if (dict.facets.has(name))
422
+ return name;
423
+ for (const f of dict.facets.values())
424
+ if (f.aliases.includes(name))
425
+ return f.key;
426
+ return undefined;
427
+ }
428
+ if (sort === "kind")
429
+ return dict.kinds.has(name) ? name : undefined;
430
+ if (sort === "class")
431
+ return dict.classes.has(name) ? name : undefined;
432
+ return name;
433
+ }
434
+ const HEX = /^#[0-9A-Fa-f]{6}$/;
435
+ /** The longest color name: a word or a short phrase (1.4.9a). */
436
+ export const COLOR_NAME_LENGTH = 60;
437
+ /** A color (1.4.9a): a hex code alone; or a name, with an optional hex code beside it, and nothing else. */
438
+ export function colorOk(c) {
439
+ if (typeof c === "string")
440
+ return HEX.test(c);
441
+ if (!isObj(c) || typeof c.$color !== "string")
442
+ return false;
443
+ const name = c.$color.trim();
444
+ if (!name || name !== c.$color || [...name].length > COLOR_NAME_LENGTH || /[\u0000-\u001f]/.test(name))
445
+ return false;
446
+ if ("hex" in c && (typeof c.hex !== "string" || !HEX.test(c.hex)))
447
+ return false;
448
+ return Object.keys(c).every((k) => k === "$color" || k === "hex");
449
+ }
450
+ /** Check one scalar against its facet: an outcome and an optional flag. */
451
+ export function checkScalar(f, v) {
452
+ const c = core(v);
453
+ if (isObj(c) && "$empty" in c)
454
+ return { outcome: "absorbed" };
455
+ switch (f.type) {
456
+ case "number": {
457
+ let amount = null;
458
+ if (typeof c === "string" && NUMBER.test(c) && !f.unit)
459
+ amount = c;
460
+ if (isObj(c) && "$qty" in c && c.unit === f.unit)
461
+ amount = String(c.$qty);
462
+ if (isObj(c) && "$money" in c && (f.unit === "currency" || c.currency === f.unit))
463
+ amount = String(c.$money);
464
+ // A spelling the units table lacks is a unit question for review (11.9), not a contradiction.
465
+ if (amount === null && isObj(c) && "$qty" in c && f.unit && unitOf(String(c.unit)) === null)
466
+ return { outcome: "new", cites: { unit: String(c.unit) } };
467
+ if (amount === null)
468
+ return { outcome: "contradiction" };
469
+ if (f.range && (Number(amount) < Number(f.range.min) || Number(amount) > Number(f.range.max)))
470
+ return { outcome: "absorbed", flag: "range" };
471
+ return { outcome: "absorbed" };
472
+ }
473
+ case "date": {
474
+ const parts = typeof c === "string" ? dateParts(c) : null;
475
+ if (!parts)
476
+ return { outcome: "contradiction" };
477
+ const timed = RANK[parts.precision] >= RANK.hour;
478
+ // A moment carries its offset; a local wall-clock date never does (1.4.5).
479
+ if (timed && (f.zone === "local" ? parts.offset !== null : parts.offset === null))
480
+ return { outcome: "contradiction" };
481
+ const want = f.precision ?? "any";
482
+ if (want !== "any" && RANK[parts.precision] < RANK[want])
483
+ return { outcome: "absorbed", flag: "precision" };
484
+ return { outcome: "absorbed" };
485
+ }
486
+ case "time": {
487
+ const m = typeof c === "string" ? c.match(TIME) : null;
488
+ if (!m || Number(m[1]) > 23 || Number(m[2]) > 59 || (m[3] !== undefined && Number(m[3]) > 59))
489
+ return { outcome: "contradiction" };
490
+ return { outcome: "absorbed" };
491
+ }
492
+ case "yes-no":
493
+ return typeof c === "boolean" ? { outcome: "absorbed" } : { outcome: "contradiction" };
494
+ case "link": {
495
+ if (!isObj(c) || !("$link" in c))
496
+ return { outcome: "contradiction" };
497
+ // A definition link holds `def:<sort>:<name>`, its own sort's (4.2.2, revision 20); a record link any id.
498
+ const sort = definitionSortOf(f);
499
+ if (sort && !definitionName(String(c.$link), sort))
500
+ return { outcome: "contradiction" };
501
+ return { outcome: "absorbed" };
502
+ }
503
+ case "image":
504
+ return isObj(c) && "$image" in c ? { outcome: "absorbed" } : { outcome: "contradiction" };
505
+ case "color":
506
+ return colorOk(c) ? { outcome: "absorbed" } : { outcome: "contradiction" };
507
+ case "choice": {
508
+ if (typeof c !== "string")
509
+ return { outcome: "contradiction" };
510
+ if ((f.values ?? []).some((x) => x.value === c))
511
+ return { outcome: "absorbed" };
512
+ return f.fixed ? { outcome: "contradiction" } : { outcome: "new" };
513
+ }
514
+ case "compound":
515
+ return isObj(c) ? { outcome: "absorbed" } : { outcome: "contradiction" };
516
+ default: {
517
+ if (typeof c !== "string")
518
+ return { outcome: "contradiction" };
519
+ if (f.length !== undefined && [...c].length > f.length)
520
+ return { outcome: "absorbed", flag: "length" };
521
+ return { outcome: "absorbed" };
522
+ }
523
+ }
524
+ }
525
+ function outcome(record, address, r, cites) {
526
+ const o = { record, address, outcome: r.outcome };
527
+ if (r.flag)
528
+ o.flag = r.flag;
529
+ if (cites)
530
+ o.cites = cites;
531
+ else if (r.outcome === "contradiction")
532
+ o.cites = { type: address.replace(/\[.*$/, "").split(".").at(-1) };
533
+ return o;
534
+ }
535
+ function checkValue(record, f, key, v, address, narrow, dict) {
536
+ const items = Array.isArray(v) ? v : null;
537
+ const pickLimit = narrow?.pick ?? f.pick;
538
+ if (items) {
539
+ if (pickLimit !== "any" && items.length > Number(pickLimit)) {
540
+ return [{ record, address, outcome: "contradiction", cites: { type: f.key } }];
541
+ }
542
+ return items.map((item) => itemOutcome(record, f, key, item, `${address}[${JSON.stringify(itemText(f, item))}]`, narrow, dict));
543
+ }
544
+ return [itemOutcome(record, f, key, v, address, narrow, dict)];
545
+ }
546
+ function citeLine(cls, l) {
547
+ return `${cls}: ${l.text}`;
548
+ }
549
+ function itemOutcome(record, f, _key, v, address, narrow, dict) {
550
+ const base = checkScalar(f, v);
551
+ // A definition link naming nothing the dictionary holds is kept and flagged (4.2.2): a package may come later.
552
+ const sort = definitionSortOf(f);
553
+ const c0 = core(v);
554
+ if (dict && sort && base.outcome === "absorbed" && !base.flag && (sort === "facet" || sort === "kind" || sort === "class") && isObj(c0) && "$link" in c0 && !resolveDefinition(dict, String(c0.$link), sort))
555
+ return outcome(record, address, { outcome: "absorbed", flag: "unknown" });
556
+ const c = core(v);
557
+ if (narrow?.values && typeof c === "string" && !(isObj(c) && "$empty" in c) && !narrow.values.includes(c)) {
558
+ const by = narrow.from.find((x) => x.line.values && !x.line.values.includes(c));
559
+ return outcome(record, address, { outcome: "contradiction" }, { rule: by ? citeLine(by.cls, by.line) : f.key });
560
+ }
561
+ return outcome(record, address, base);
562
+ }
563
+ function isEmptyValue(v) {
564
+ return v === undefined || (isObj(v) && v.$empty === "unknown");
565
+ }
566
+ /** Check a record: every value against its facet and worn classes, required facets, and parts. */
567
+ export function checkRecord(r, dict) {
568
+ const outcomes = [];
569
+ const worn = (r.wears ?? []).filter((w) => dict.classes.has(w));
570
+ const resolved = resolve(dict, worn);
571
+ const byFacet = new Map(resolved.map((l) => [l.facet, l]));
572
+ const asked = [];
573
+ const missing = [];
574
+ for (const l of resolved) {
575
+ let holds = true;
576
+ if (l.when)
577
+ holds = evaluate(parseCondition(l.when), r.values);
578
+ if (holds !== true)
579
+ continue;
580
+ asked.push(l.facet);
581
+ if (l.required && isEmptyValue(r.values[l.facet])) {
582
+ missing.push(l.facet);
583
+ const by = l.from.find((x) => x.line.required);
584
+ outcomes.push({ record: r.id, address: l.facet, outcome: "incomplete", cites: { rule: by ? citeLine(by.cls, by.line) : l.facet } });
585
+ }
586
+ }
587
+ for (const [key, v] of Object.entries(r.values)) {
588
+ const f = dict.facets.get(key);
589
+ if (!f) {
590
+ outcomes.push({ record: r.id, address: key, outcome: "unknown" });
591
+ continue;
592
+ }
593
+ outcomes.push(...checkValue(r.id, f, key, v, key, byFacet.get(key), dict));
594
+ }
595
+ const slots = worn.flatMap((w) => (dict.classes.get(w)?.parts ?? []).map((s) => ({ cls: w, s })));
596
+ for (const p of r.parts ?? []) {
597
+ if (!isObj(p))
598
+ continue;
599
+ const row = String(p.$row);
600
+ const wears = Array.isArray(p.wears) ? p.wears.map(String) : [];
601
+ const slot = slots.find((x) => wears.includes(x.s.wears));
602
+ const at = `parts[${row}]`;
603
+ const cite = slot ? { type: `${slot.cls}: ${slot.s.slot}` } : undefined;
604
+ if (slot && !slot.s.fungible && (row === `${slot.s.slot}s` || row === `${slot.s.slot}es`)) {
605
+ outcomes.push({ record: r.id, address: at, outcome: "contradiction", cites: cite, reason: "plural of a non-fungible slot" });
606
+ }
607
+ const values = isObj(p.values) ? p.values : {};
608
+ for (const [key, v] of Object.entries(values)) {
609
+ const address = `${at}.${key}`;
610
+ if (key === "crubal:count") {
611
+ if (slot && !slot.s.fungible) {
612
+ outcomes.push({ record: r.id, address, outcome: "contradiction", cites: cite, reason: "count on a non-fungible slot" });
613
+ continue;
614
+ }
615
+ }
616
+ const f = dict.facets.get(key);
617
+ if (!f) {
618
+ outcomes.push({ record: r.id, address, outcome: "unknown" });
619
+ continue;
620
+ }
621
+ outcomes.push(...checkValue(r.id, f, key, v, address, undefined, dict));
622
+ }
623
+ }
624
+ const summary = { record: r.id, asked, outcome: missing.length ? "incomplete" : "complete" };
625
+ if (missing.length)
626
+ summary.missing = missing;
627
+ return { outcomes, summary };
628
+ }
629
+ //# sourceMappingURL=dictionary.js.map