aontu 0.53.0 → 0.55.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 (197) hide show
  1. package/dist/aontu.d.ts +3 -2
  2. package/dist/aontu.js +36 -7
  3. package/dist/aontu.js.map +1 -1
  4. package/dist/cli.d.ts +2 -1
  5. package/dist/cli.js +500 -8
  6. package/dist/cli.js.map +1 -1
  7. package/dist/ctx.d.ts +5 -0
  8. package/dist/ctx.js +1 -0
  9. package/dist/ctx.js.map +1 -1
  10. package/dist/diff.js.map +1 -1
  11. package/dist/err.js +7 -1
  12. package/dist/err.js.map +1 -1
  13. package/dist/graph.d.ts +2 -5
  14. package/dist/graph.js +83 -46
  15. package/dist/graph.js.map +1 -1
  16. package/dist/hcanon.js +9 -10
  17. package/dist/hcanon.js.map +1 -1
  18. package/dist/hints.js +94 -26
  19. package/dist/hints.js.map +1 -1
  20. package/dist/jsonschema.js +34 -0
  21. package/dist/jsonschema.js.map +1 -1
  22. package/dist/lang.js +593 -191
  23. package/dist/lang.js.map +1 -1
  24. package/dist/lsp.d.ts +1 -1
  25. package/dist/lsp.js +86 -6
  26. package/dist/lsp.js.map +1 -1
  27. package/dist/mcp.js +153 -6
  28. package/dist/mcp.js.map +1 -1
  29. package/dist/mod-tool.js +42 -8
  30. package/dist/mod-tool.js.map +1 -1
  31. package/dist/mod.d.ts +4 -0
  32. package/dist/mod.js +97 -2
  33. package/dist/mod.js.map +1 -1
  34. package/dist/patch.d.ts +5 -0
  35. package/dist/patch.js +25 -25
  36. package/dist/patch.js.map +1 -1
  37. package/dist/provenance.d.ts +1 -0
  38. package/dist/provenance.js +2 -1
  39. package/dist/provenance.js.map +1 -1
  40. package/dist/query.js.map +1 -1
  41. package/dist/reach.d.ts +1 -0
  42. package/dist/reach.js +49 -21
  43. package/dist/reach.js.map +1 -1
  44. package/dist/relation.d.ts +4 -0
  45. package/dist/relation.js +125 -200
  46. package/dist/relation.js.map +1 -1
  47. package/dist/sig.d.ts +25 -0
  48. package/dist/sig.js +277 -0
  49. package/dist/sig.js.map +1 -0
  50. package/dist/sigdecl.d.ts +2 -0
  51. package/dist/sigdecl.js +11 -0
  52. package/dist/sigdecl.js.map +1 -0
  53. package/dist/siggate.d.ts +4 -0
  54. package/dist/siggate.js +90 -0
  55. package/dist/siggate.js.map +1 -0
  56. package/dist/std.js +75 -16
  57. package/dist/std.js.map +1 -1
  58. package/dist/subsume.js +57 -10
  59. package/dist/subsume.js.map +1 -1
  60. package/dist/tsconfig.tsbuildinfo +1 -1
  61. package/dist/unify.d.ts +2 -2
  62. package/dist/unify.js +93 -114
  63. package/dist/unify.js.map +1 -1
  64. package/dist/utility.d.ts +1 -2
  65. package/dist/utility.js +7 -61
  66. package/dist/utility.js.map +1 -1
  67. package/dist/val/AggFuncVal.d.ts +12 -1
  68. package/dist/val/AggFuncVal.js +165 -3
  69. package/dist/val/AggFuncVal.js.map +1 -1
  70. package/dist/val/BagVal.d.ts +2 -0
  71. package/dist/val/BagVal.js +56 -8
  72. package/dist/val/BagVal.js.map +1 -1
  73. package/dist/val/ConstraintVal.js +33 -5
  74. package/dist/val/ConstraintVal.js.map +1 -1
  75. package/dist/val/ContainerKindVal.d.ts +35 -0
  76. package/dist/val/ContainerKindVal.js +99 -0
  77. package/dist/val/ContainerKindVal.js.map +1 -0
  78. package/dist/val/CopyFuncVal.js +0 -7
  79. package/dist/val/CopyFuncVal.js.map +1 -1
  80. package/dist/val/DisjunctVal.d.ts +1 -2
  81. package/dist/val/DisjunctVal.js +146 -39
  82. package/dist/val/DisjunctVal.js.map +1 -1
  83. package/dist/val/ExpectVal.js +37 -2
  84. package/dist/val/ExpectVal.js.map +1 -1
  85. package/dist/val/FuncBaseVal.d.ts +1 -0
  86. package/dist/val/FuncBaseVal.js +19 -8
  87. package/dist/val/FuncBaseVal.js.map +1 -1
  88. package/dist/val/GraphAtomVal.d.ts +39 -0
  89. package/dist/val/GraphAtomVal.js +184 -0
  90. package/dist/val/GraphAtomVal.js.map +1 -0
  91. package/dist/val/JunctionVal.js +22 -5
  92. package/dist/val/JunctionVal.js.map +1 -1
  93. package/dist/val/ListVal.js +27 -34
  94. package/dist/val/ListVal.js.map +1 -1
  95. package/dist/val/MapVal.d.ts +1 -0
  96. package/dist/val/MapVal.js +82 -35
  97. package/dist/val/MapVal.js.map +1 -1
  98. package/dist/val/PathFuncVal.d.ts +2 -2
  99. package/dist/val/PathFuncVal.js +75 -16
  100. package/dist/val/PathFuncVal.js.map +1 -1
  101. package/dist/val/PathVal.d.ts +25 -0
  102. package/dist/val/PathVal.js +150 -0
  103. package/dist/val/PathVal.js.map +1 -0
  104. package/dist/val/PlusOpVal.d.ts +2 -1
  105. package/dist/val/PlusOpVal.js +50 -35
  106. package/dist/val/PlusOpVal.js.map +1 -1
  107. package/dist/val/PrefVal.d.ts +2 -0
  108. package/dist/val/PrefVal.js +159 -32
  109. package/dist/val/PrefVal.js.map +1 -1
  110. package/dist/val/RecurseVal.d.ts +19 -0
  111. package/dist/val/RecurseVal.js +217 -0
  112. package/dist/val/RecurseVal.js.map +1 -0
  113. package/dist/val/RefVal.d.ts +2 -1
  114. package/dist/val/RefVal.js +105 -72
  115. package/dist/val/RefVal.js.map +1 -1
  116. package/dist/val/ReferFuncVal.d.ts +30 -7
  117. package/dist/val/ReferFuncVal.js +395 -94
  118. package/dist/val/ReferFuncVal.js.map +1 -1
  119. package/dist/val/ScalarKindVal.d.ts +4 -2
  120. package/dist/val/ScalarKindVal.js +12 -1
  121. package/dist/val/ScalarKindVal.js.map +1 -1
  122. package/dist/val/SuperFuncVal.d.ts +4 -2
  123. package/dist/val/SuperFuncVal.js +118 -14
  124. package/dist/val/SuperFuncVal.js.map +1 -1
  125. package/dist/val/TopVal.d.ts +1 -1
  126. package/dist/val/Val.d.ts +2 -3
  127. package/dist/val/Val.js +39 -20
  128. package/dist/val/Val.js.map +1 -1
  129. package/dist/val/arith.js +4 -1
  130. package/dist/val/arith.js.map +1 -1
  131. package/dist/vet.d.ts +1 -0
  132. package/dist/vet.js +32 -1
  133. package/dist/vet.js.map +1 -1
  134. package/dist/view.d.ts +90 -0
  135. package/dist/view.js +2168 -0
  136. package/dist/view.js.map +1 -0
  137. package/grammar/aontu.gbnf +18 -10
  138. package/grammar/aontu.lark +15 -10
  139. package/grammar/aontu.tmLanguage.json +184 -0
  140. package/package.json +10 -3
  141. package/skill/grammar-card.md +1 -2
  142. package/src/aontu.ts +37 -7
  143. package/src/cli.ts +553 -8
  144. package/src/ctx.ts +20 -0
  145. package/src/diff.ts +4 -2
  146. package/src/err.ts +8 -1
  147. package/src/graph.ts +125 -75
  148. package/src/hcanon.ts +9 -11
  149. package/src/hints.ts +112 -29
  150. package/src/jsonschema.ts +41 -0
  151. package/src/lang.ts +642 -203
  152. package/src/lsp.ts +75 -6
  153. package/src/mcp.ts +164 -6
  154. package/src/mod-tool.ts +48 -9
  155. package/src/mod.ts +110 -1
  156. package/src/patch.ts +31 -27
  157. package/src/provenance.ts +8 -1
  158. package/src/query.ts +4 -2
  159. package/src/reach.ts +52 -23
  160. package/src/relation.ts +139 -236
  161. package/src/sig.ts +345 -0
  162. package/src/sigdecl.ts +11 -0
  163. package/src/siggate.ts +144 -0
  164. package/src/std.ts +77 -16
  165. package/src/subsume.ts +59 -10
  166. package/src/unify.ts +102 -125
  167. package/src/utility.ts +7 -67
  168. package/src/val/AggFuncVal.ts +231 -4
  169. package/src/val/BagVal.ts +58 -9
  170. package/src/val/ConstraintVal.ts +34 -5
  171. package/src/val/ContainerKindVal.ts +158 -0
  172. package/src/val/CopyFuncVal.ts +0 -7
  173. package/src/val/DisjunctVal.ts +152 -40
  174. package/src/val/ExpectVal.ts +39 -4
  175. package/src/val/FuncBaseVal.ts +21 -8
  176. package/src/val/GraphAtomVal.ts +264 -0
  177. package/src/val/JunctionVal.ts +23 -6
  178. package/src/val/ListVal.ts +30 -37
  179. package/src/val/MapVal.ts +87 -39
  180. package/src/val/PathFuncVal.ts +107 -19
  181. package/src/val/PathVal.ts +221 -0
  182. package/src/val/PlusOpVal.ts +56 -37
  183. package/src/val/PrefVal.ts +186 -38
  184. package/src/val/RecurseVal.ts +285 -0
  185. package/src/val/RefVal.ts +105 -83
  186. package/src/val/ReferFuncVal.ts +445 -100
  187. package/src/val/ScalarKindVal.ts +12 -0
  188. package/src/val/SuperFuncVal.ts +137 -13
  189. package/src/val/TopVal.ts +1 -1
  190. package/src/val/Val.ts +44 -35
  191. package/src/val/arith.ts +4 -1
  192. package/src/vet.ts +41 -4
  193. package/src/view.ts +2882 -0
  194. package/dist/val/IdFuncVal.d.ts +0 -13
  195. package/dist/val/IdFuncVal.js +0 -54
  196. package/dist/val/IdFuncVal.js.map +0 -1
  197. package/src/val/IdFuncVal.ts +0 -91
package/dist/view.js ADDED
@@ -0,0 +1,2168 @@
1
+ "use strict";
2
+ /* Copyright (c) 2026 Richard Rodger, MIT License */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.viewDefaultProfile = viewDefaultProfile;
5
+ exports.view = view;
6
+ exports.viewTree = viewTree;
7
+ exports.viewSet = viewSet;
8
+ // THE VIEWS (docs/design/VIEWS.0.md and VIEWS-ORDER.0.md): figures of
9
+ // an evaluated document, drawn as deterministic text a golden diff can
10
+ // check. Seven kinds:
11
+ //
12
+ // tree the dependency tree of one relation
13
+ // matrix the dependency matrix over one relation, in canon or
14
+ // partition order, with closure and the unmirrored mark
15
+ // graph the node-link drawing, as Mermaid, DOT or an ER diagram
16
+ // layer the architecture layers: stacked bands, one per value of
17
+ // a field, with the relation's upward edges called out
18
+ // sets the set-intersection panel over a named set family
19
+ // layers which document contributed which path (provenance)
20
+ // ladder the meet ladder at one path (the `why` record, drawn)
21
+ // poset the subsumption order over a set of documents
22
+ //
23
+ // A view consumes a REPORT, never the Val tree: the edge set `graphOf`
24
+ // derives (ts/src/graph.ts), the relation declarations, the generated
25
+ // value, the provenance record, the subsumption verdict. That is what
26
+ // keeps the two ports at parity -- Go's exported Val interface is five
27
+ // methods, and a Val-walking view would be TypeScript-only on the day
28
+ // it landed.
29
+ //
30
+ // Everything here is deterministic: nodes and edges are sorted by code
31
+ // point before emission, nothing iterates a map in insertion order, no
32
+ // coordinate is computed and no number is formatted beyond its decimal
33
+ // digits. The Go twin is go/view.go; what the two ports must agree on
34
+ // -- the rendered text, the loss report and the refusals -- is
35
+ // test/spec/view.tsv.
36
+ //
37
+ // EVERY RUN CARRIES A LOSS REPORT: what the figure could not draw, or
38
+ // drew differently from the model, aggregated by code with a count.
39
+ // Three codes are informational -- `edges_deduped` (several written
40
+ // positions, one fact), `inverse_suppressed` (a declared mirror,
41
+ // implied by the edge drawn) and `crossings` (a property of the
42
+ // emitted order, not of the model) -- and leave the verdict `rendered`. Every
43
+ // other code makes it `lossy`, which `--strict` refuses: a figure that
44
+ // quietly omits things is the failure this capability exists to avoid.
45
+ const node_path_1 = require("node:path");
46
+ const aontu_1 = require("./aontu");
47
+ const vet_1 = require("./vet");
48
+ const graph_1 = require("./graph");
49
+ const keyorder_1 = require("./keyorder");
50
+ const provenance_1 = require("./provenance");
51
+ const query_1 = require("./query");
52
+ const subsume_1 = require("./subsume");
53
+ // The text profile's mechanism: the eight named colours, `bold` and
54
+ // `dim`, and nothing else. `label` is unstyled -- an entity's own name
55
+ // is the figure's content, not a mark about it.
56
+ const SGR = {
57
+ label: '', muted: '2', rule: '2', direct: '1', closure: '36',
58
+ unmirrored: '33', upward: '31', repeat: '2', bar: '36', hole: '2',
59
+ };
60
+ const PLAIN = (_role, text) => text;
61
+ const ANSI = (role, text) => '' === SGR[role] || '' === text
62
+ ? text : `\x1b[${SGR[role]}m${text}\x1b[0m`;
63
+ const painter = (style) => 'ansi' === style ? ANSI : PLAIN;
64
+ // The style a figure gets when the caller named none. An SVG carries
65
+ // its stylesheet, which is what makes it standalone and what every
66
+ // pinned golden holds; everything else carries no mechanism, since a
67
+ // library cannot see whether its output is a terminal.
68
+ const styleOf = (style, as) => style ?? ('svg' === as ? 'css' : 'none');
69
+ // Each kind's profiles, the first being its default. There is no
70
+ // global default, because there is no sensible text form of a
71
+ // node-link drawing and no sensible Mermaid form of a matrix.
72
+ const PROFILES = {
73
+ doc: ['text', 'svg'],
74
+ tree: ['text', 'svg'],
75
+ matrix: ['text', 'svg'],
76
+ graph: ['mermaid', 'dot', 'er'],
77
+ layer: ['text', 'mermaid', 'svg'],
78
+ sets: ['text', 'svg'],
79
+ layers: ['text', 'svg'],
80
+ ladder: ['mermaid', 'dot'],
81
+ poset: ['mermaid', 'dot'],
82
+ };
83
+ // The profile a kind draws into when none is asked for. The CLI needs
84
+ // it to resolve `--style auto` BEFORE the library runs, since the
85
+ // mechanism is the profile's.
86
+ function viewDefaultProfile(kind) {
87
+ return PROFILES[kind]?.[0];
88
+ }
89
+ // Loss codes that describe the drawing rather than a gap in it.
90
+ const INFORMATIONAL = ['edges_deduped', 'inverse_suppressed', 'crossings'];
91
+ const DEFAULT_MAX_ROWS = 60;
92
+ // The separator inside a composite map key: a character no path holds.
93
+ const SEP = '\u0000';
94
+ // ---------------------------------------------------------------------
95
+ // Findings
96
+ function finding(code, cls, path, message, note) {
97
+ return {
98
+ code,
99
+ class: cls,
100
+ severity: 'error',
101
+ path,
102
+ message,
103
+ sites: [],
104
+ ...(undefined === note ? {} : { note }),
105
+ };
106
+ }
107
+ // A relation that draws nothing is a typo, and is refused for the same
108
+ // reason a misspelled root is: an empty figure and a misspelled name
109
+ // are the same file on disk, so the one that means nothing must not be
110
+ // renderable. NOT `refer_unresolved`: a relation name is not an
111
+ // address.
112
+ function relationFinding(relation, have) {
113
+ return finding('view_relation_unknown', 'reference', '$', `${relation} names no relation with edges in this document.`, 'relations with edges: ' + have.join(', '));
114
+ }
115
+ // A root is a node of the DRAWN graph, the rule the node set follows:
116
+ // a path that exists in the document but takes no part in the relation
117
+ // is not in the drawing, and a root naming it is refused rather than
118
+ // drawn as an empty tree.
119
+ function rootFinding(root, relation, nodes) {
120
+ return finding('refer_unresolved', 'reference', '$', `${root} is not a node of the ` +
121
+ `${undefined === relation ? '' : relation + ' '}graph.`, 0 === nodes.length ? undefined : 'nodes in the graph: ' + nodes.join(', '));
122
+ }
123
+ // `--max-rows` is a REFUSAL, and the message names the narrowing
124
+ // options.
125
+ function rowsFinding(rows, max, narrow) {
126
+ return finding('view_rows_exceeded', 'budget', '$', `The figure has ${rows} rows, above --max-rows ${max}; ` +
127
+ `narrow it with ${narrow}, or raise the limit.`, `rows: ${rows}, max: ${max}`);
128
+ }
129
+ // An inline piece may not contain a line terminator: a line is a
130
+ // line, which is what makes every renderer a total fold.
131
+ function lineBreakFinding(path) {
132
+ return finding('view_line_break', 'parse', path, 'A label holds a line terminator, which no figure line can carry.');
133
+ }
134
+ // A prefix test on PATHS, not strings: `$.a` covers `$.a.b` and `$.a`
135
+ // itself, and not `$.ab`.
136
+ function under(path, at) {
137
+ return undefined === at || path === at || path.startsWith(at + '.');
138
+ }
139
+ // The deduplicated edge set, with the hidden contributions and the
140
+ // out-of-scope edges removed and the loss report told.
141
+ //
142
+ // `graphOf` emits one edge per WRITTEN POSITION by design, because each
143
+ // `at` is an editable site, and an identity-merged model declares each
144
+ // entity at two positions. Deduplication is part of the extraction
145
+ // contract, not a renderer's private cleverness, and the count is
146
+ // reported so nobody has to guess which number they are looking at.
147
+ //
148
+ // A HIDDEN edge -- one written inside a `hide()`-marked subtree -- is
149
+ // not drawn. A figure is committed to a repository, so anything drawn
150
+ // is disclosed, and the subtree's whole purpose is to say "not
151
+ // output". It is reported with its path instead, and `--strict`
152
+ // refuses the figure.
153
+ function triplesOf(graph, at, loss) {
154
+ const edges = graph.edges;
155
+ const hidden = [];
156
+ const seen = new Map();
157
+ let positions = 0;
158
+ for (const e of edges) {
159
+ if (true === e.hidden) {
160
+ hidden.push(e.at);
161
+ continue;
162
+ }
163
+ if (!under(e.from, at) || !under(e.to, at)) {
164
+ continue;
165
+ }
166
+ positions++;
167
+ seen.set(e.from + SEP + e.key + SEP + e.to, { from: e.from, key: e.key, to: e.to });
168
+ }
169
+ if (0 < hidden.length) {
170
+ loss.push({
171
+ code: 'hidden_contribution', count: hidden.length,
172
+ detail: hidden.sort(keyorder_1.cmpCodePoint),
173
+ });
174
+ }
175
+ // A link under an UNRESOLVED DISJUNCTION is not an edge (ADR-007),
176
+ // and the figure says so rather than dropping it in silence: the
177
+ // document has not decided, and a drawing that quietly picked an arm
178
+ // would be inventing the decision.
179
+ const undecided = (graph.disjunct ?? []).filter((p) => under(p, at));
180
+ if (0 < undecided.length) {
181
+ loss.push({
182
+ code: 'edges_in_disjunct', count: undecided.length, detail: undecided,
183
+ });
184
+ }
185
+ const out = [...seen.values()].sort((a, b) => (0, keyorder_1.cmpCodePoint)(a.from, b.from) || (0, keyorder_1.cmpCodePoint)(a.key, b.key)
186
+ || (0, keyorder_1.cmpCodePoint)(a.to, b.to));
187
+ if (out.length < positions) {
188
+ loss.push({
189
+ code: 'edges_deduped', count: positions - out.length,
190
+ detail: [`${positions} written positions -> ` +
191
+ `${out.length} distinct triples`],
192
+ });
193
+ }
194
+ return out;
195
+ }
196
+ // The relations with edges, in code-point order.
197
+ function keysOf(triples) {
198
+ return [...new Set(triples.map((e) => e.key))].sort(keyorder_1.cmpCodePoint);
199
+ }
200
+ // The node set is what the drawn edges CONNECT, in code-point order.
201
+ function nodesOf(triples) {
202
+ const ns = new Set();
203
+ for (const e of triples) {
204
+ ns.add(e.from);
205
+ ns.add(e.to);
206
+ }
207
+ return [...ns].sort(keyorder_1.cmpCodePoint);
208
+ }
209
+ // THE SHORTEST SUFFIX THAT IS STILL UNIQUE, as a node's visible label.
210
+ //
211
+ // A node's name IS its path (ADR-014), and the paths in a real model
212
+ // are long: eight nodes labelled `$.catalog.domains.identity.services.auth`
213
+ // and its siblings is a correct diagram nobody can read. The label is
214
+ // therefore the fewest trailing segments that still tell this node from
215
+ // every other in the same drawing -- `auth` where that is unambiguous,
216
+ // `identity.auth` where it is not.
217
+ //
218
+ // The rule is a function of the node SET, so a drawing is deterministic
219
+ // while two drawings of different slices may label the same node
220
+ // differently -- which is correct, because uniqueness is a property of
221
+ // the set being drawn. The search is unbounded on purpose: at the full
222
+ // segment count the candidate is the whole path, which no other node
223
+ // shares, so it always ends.
224
+ function labelsOf(nodes) {
225
+ const segs = new Map(nodes.map((n) => [n, n.replace(/^\$\.?/, '').split('.')]));
226
+ const out = new Map();
227
+ for (const n of nodes) {
228
+ const parts = segs.get(n);
229
+ for (let take = 1;; take++) {
230
+ const cand = parts.slice(Math.max(0, parts.length - take)).join('.');
231
+ const clash = nodes.some((m) => {
232
+ const ms = segs.get(m);
233
+ return m !== n &&
234
+ ms.slice(Math.max(0, ms.length - take)).join('.') === cand;
235
+ });
236
+ if (!clash) {
237
+ out.set(n, cand);
238
+ break;
239
+ }
240
+ }
241
+ }
242
+ return out;
243
+ }
244
+ // Reachability over a directed edge set: node -> the set of nodes it
245
+ // reaches in one or more steps. Iterative closure, O(n * e), which is
246
+ // nothing at the sizes a figure can hold.
247
+ function reachOf(nodes, succ) {
248
+ const out = new Map();
249
+ for (const n of nodes) {
250
+ const seen = new Set();
251
+ const stack = [...succ.get(n)];
252
+ while (0 < stack.length) {
253
+ const m = stack.pop();
254
+ if (!seen.has(m)) {
255
+ seen.add(m);
256
+ stack.push(...succ.get(m));
257
+ }
258
+ }
259
+ out.set(n, seen);
260
+ }
261
+ return out;
262
+ }
263
+ // ---------------------------------------------------------------------
264
+ // Text helpers, all on code units, none formatting a number
265
+ const pad = (s, n) => s + ' '.repeat(Math.max(0, n - s.length));
266
+ const lpad = (s, n) => ' '.repeat(Math.max(0, n - s.length)) + s;
267
+ const widest = (ss) => ss.reduce((w, s) => Math.max(w, s.length), 0);
268
+ // ---------------------------------------------------------------------
269
+ // Identifiers and escapes (VIEWS.0.md, "The renderers and the profiles")
270
+ // Injective by construction, with two disjoint prefixes and one
271
+ // predicate: `n_` + the name when its first code point is an ASCII
272
+ // letter and every code point is an ASCII letter, digit or `_`;
273
+ // otherwise `nq_` + the name with every other code point replaced by
274
+ // `_` and its lower-case hex. A code-point class test, not a regular
275
+ // expression: pattern matching is the one subsystem with a stated
276
+ // RE2-versus-RegExp divergence, and an encoder runs on every name.
277
+ function ident(name) {
278
+ const letter = (c) => (65 <= c && c <= 90) || (97 <= c && c <= 122);
279
+ const digit = (c) => 48 <= c && c <= 57;
280
+ const cps = [...name].map((ch) => ch.codePointAt(0));
281
+ const plain = 0 < cps.length && letter(cps[0]) &&
282
+ cps.every((c) => letter(c) || digit(c) || 95 === c);
283
+ if (plain) {
284
+ return 'n_' + name;
285
+ }
286
+ let out = 'nq_';
287
+ for (const c of cps) {
288
+ out += letter(c) || digit(c)
289
+ ? String.fromCodePoint(c) : '_' + lpad(c.toString(16), 2);
290
+ }
291
+ return out;
292
+ }
293
+ // One pass, per code point, from a table keyed by DECIMAL CODE POINT.
294
+ // Mermaid: numeric entities only, never HTML names, so there is no
295
+ // name table to diverge; 124 is in it because `|` is the edge-label
296
+ // delimiter. DOT: the two escapes that also make it impossible for user
297
+ // text to forge DOT's own `\n` / `\l` / `\r` justification escapes.
298
+ const MERMAID_ESC = {
299
+ 34: '#34;', 35: '#35;', 38: '#38;', 60: '#60;', 62: '#62;',
300
+ 123: '#123;', 124: '#124;', 125: '#125;',
301
+ };
302
+ const DOT_ESC = { 34: '\\"', 92: '\\\\' };
303
+ function escape(text, table) {
304
+ let out = '';
305
+ for (const ch of text) {
306
+ const rep = table[ch.codePointAt(0)];
307
+ out += undefined === rep ? ch : rep;
308
+ }
309
+ return out;
310
+ }
311
+ // U+000A, U+000D, U+2028 and U+2029: the four code points that end a
312
+ // line somewhere.
313
+ function hasLineBreak(text) {
314
+ return /[\n\r\u2028\u2029]/.test(text);
315
+ }
316
+ // ---------------------------------------------------------------------
317
+ // SVG (VIEWS.0.md, "No SVG in v1" -- the phase after the text kinds)
318
+ //
319
+ // The cell-based kinds draw into SVG under the INTEGER RULE: every
320
+ // coordinate is a whole number of a fixed cell -- 8 units per
321
+ // character, 20 per line -- from the same counts that lay the text
322
+ // figure out, so no font is measured and both ports emit the same
323
+ // bytes. The reader's browser shapes the text; the geometry is ours.
324
+ // A figure is standalone (its own style block, with default colours)
325
+ // and themeable (every colour a CSS variable a host page can set).
326
+ const CH = 8;
327
+ const LH = 20;
328
+ const PAD = 8;
329
+ const SVG_ESC = {
330
+ 34: '&quot;', 38: '&amp;', 60: '&lt;', 62: '&gt;',
331
+ };
332
+ const SVG_STYLE = '<style>' +
333
+ '.av{font-family:ui-monospace,Menlo,Consolas,monospace;font-size:13px}' +
334
+ '.av-t{fill:var(--av-ink,#1f2328)}' +
335
+ '.av-m{fill:var(--av-muted,#6e7781)}' +
336
+ '.av-box{fill:var(--av-bg,#f6f8fa);stroke:var(--av-rule,#8c959f);stroke-width:1}' +
337
+ '.av-cell{fill:var(--av-bg,#f6f8fa);stroke:var(--av-rule-faint,#d0d7de);stroke-width:1}' +
338
+ '.av-direct{fill:var(--av-ink,#1f2328);stroke:var(--av-rule-faint,#d0d7de);stroke-width:1}' +
339
+ '.av-closure{fill:var(--av-closure,#9ec5fe);stroke:var(--av-rule-faint,#d0d7de);stroke-width:1}' +
340
+ '.av-unmirrored{fill:var(--av-warn,#e3b341);stroke:var(--av-rule-faint,#d0d7de);stroke-width:1}' +
341
+ '.av-line{stroke:var(--av-rule,#8c959f);stroke-width:1;fill:none}' +
342
+ '.av-up{stroke:var(--av-alert,#d1242f);stroke-width:1.5;fill:none;stroke-dasharray:4 3}' +
343
+ '.av-dot{fill:var(--av-ink,#1f2328)}' +
344
+ '.av-hole{fill:var(--av-bg,#f6f8fa);stroke:var(--av-rule-faint,#d0d7de);stroke-width:1}' +
345
+ '.av-bar{fill:var(--av-bar,#57606a)}' +
346
+ '</style>';
347
+ const svgEsc = (s) => escape(s, SVG_ESC);
348
+ // The document: a viewBox the size of the figure, the style, and the
349
+ // parts, one per line, so the bytes read as a figure and diff as one.
350
+ function svgDoc(w, h, about, parts, style) {
351
+ // The CLASSES are structure and are always written -- a rect that
352
+ // does not say whether it is a direct cell or a closure cell is not
353
+ // a figure. What `--style none` drops is the STYLESHEET, for a host
354
+ // page that has already bound the variables and would otherwise
355
+ // carry one copy of these rules per embedded figure.
356
+ return [
357
+ `<svg xmlns="http://www.w3.org/2000/svg" class="av" viewBox="0 0 ${w} ${h}" ` +
358
+ `width="${w}" height="${h}" role="img" aria-label="${svgEsc(about)}">`,
359
+ ...('css' === style ? [SVG_STYLE] : []),
360
+ ...parts,
361
+ '</svg>',
362
+ ].join('\n');
363
+ }
364
+ // A text run at a baseline. `anchor` is SVG's own vocabulary.
365
+ function svgText(x, y, cls, text, anchor) {
366
+ return `<text x="${x}" y="${y}" class="${cls}"` +
367
+ (undefined === anchor ? '' : ` text-anchor="${anchor}"`) +
368
+ `>${svgEsc(text)}</text>`;
369
+ }
370
+ // The relation a figure is over, for its description; a document with
371
+ // no edges has none to name.
372
+ const over = (relation) => undefined === relation || '' === relation ? '' : ' over ' + relation;
373
+ function svgRect(x, y, w, h, cls) {
374
+ return `<rect x="${x}" y="${y}" width="${w}" height="${h}" class="${cls}"/>`;
375
+ }
376
+ function svgPath(d, cls) {
377
+ return `<path d="${d}" class="${cls}"/>`;
378
+ }
379
+ // THE EDGE SET WITH DECLARED INVERSE PAIRS COLLAPSED to one logical
380
+ // edge, the tree's way: a relation with a declared inverse arrives
381
+ // twice -- once per direction -- and drawing it raw doubles every such
382
+ // relation.
383
+ //
384
+ // WHAT IS NOT COLLAPSED IS A MUTUAL RELATION: `a dependsOn b` and `b
385
+ // dependsOn a` are two facts under ONE key, and folding them into a
386
+ // single undirected edge erases the shortest cycle a model can have.
387
+ // The collapse is therefore per KEY PAIR rather than per node pair --
388
+ // two keys facing each other are an inverse, one key facing itself is
389
+ // a loop -- which is what makes `acyclic()`'s refusal drawable.
390
+ function collapse(triples, relation) {
391
+ const pairs = new Map();
392
+ for (const e of triples) {
393
+ const pair = [e.from, e.to].sort(keyorder_1.cmpCodePoint).join(SEP);
394
+ const group = pairs.get(pair);
395
+ if (undefined === group) {
396
+ pairs.set(pair, [e]);
397
+ }
398
+ else {
399
+ group.push(e);
400
+ }
401
+ }
402
+ const out = [];
403
+ for (const group of pairs.values()) {
404
+ // ONE KEY WINS THE PAIR, and every edge written under it stands.
405
+ // The named relation wins; otherwise the code-point-least key,
406
+ // which is arbitrary but stable. Keeping every edge under the
407
+ // winner is what preserves a MUTUAL relation, while the losing keys
408
+ // are the declared inverses, implied by the winner and not drawn
409
+ // again. With a relation named, its inverse is implied and naming
410
+ // both would double the label; without one, every key is shown,
411
+ // because picking silently would hide that two predicates are in
412
+ // play.
413
+ const keys = keysOf(group);
414
+ const named = undefined !== relation && keys.includes(relation);
415
+ const winner = named ? relation : keys[0];
416
+ const label = named ? winner : keys.join('/');
417
+ for (const e of group) {
418
+ if (e.key === winner) {
419
+ out.push({ from: e.from, to: e.to, label });
420
+ }
421
+ }
422
+ }
423
+ // One winner per pair, so (from, to) is unique and orders the set.
424
+ return out.sort((x, y) => (0, keyorder_1.cmpCodePoint)(x.from, y.from) || (0, keyorder_1.cmpCodePoint)(x.to, y.to));
425
+ }
426
+ function drawTree(all, relation, roots, max, as, style) {
427
+ const paint = painter(style);
428
+ // With a relation named, the tree is OVER THAT RELATION. A node-link
429
+ // diagram can label each edge and so draw every relation at once; a
430
+ // tree cannot without becoming unreadable, and walking two relations
431
+ // as though they were one would draw a containment the model does
432
+ // not state.
433
+ const kept = undefined === relation
434
+ ? all : all.filter((e) => e.label === relation);
435
+ if (undefined !== relation && 0 === kept.length && 0 < all.length) {
436
+ const have = [...new Set(all.flatMap((e) => e.label.split('/')))]
437
+ .sort(keyorder_1.cmpCodePoint);
438
+ return { errors: [relationFinding(relation, have)] };
439
+ }
440
+ // The node set is what the drawn relation CONNECTS. A root naming
441
+ // anything else is a typo, and it is refused rather than drawn.
442
+ const nodes = nodesOf(kept);
443
+ if (max < nodes.length) {
444
+ return {
445
+ errors: [rowsFinding(nodes.length, max, '--at, --relation or --root')],
446
+ };
447
+ }
448
+ const lab = labelsOf(nodes);
449
+ const label = (n) => lab.get(n);
450
+ const kids = new Map(nodes.map((n) => [n, []]));
451
+ for (const e of kept) {
452
+ kids.get(e.from).push({ to: e.to, label: e.label });
453
+ }
454
+ for (const list of kids.values()) {
455
+ list.sort((x, y) => (0, keyorder_1.cmpCodePoint)(label(x.to), label(y.to)));
456
+ }
457
+ // The relation is named on the branch only where more than one is
458
+ // drawn. Naming the single relation on every line of a tree that has
459
+ // exactly one is noise; leaving it off where there are two would
460
+ // hide which edge was walked.
461
+ const many = 1 < new Set(kept.map((e) => e.label)).size;
462
+ const byLabel = (a, b) => (0, keyorder_1.cmpCodePoint)(label(a), label(b));
463
+ let named;
464
+ if (0 < roots.length) {
465
+ const missing = roots.filter((r) => !kids.has(r));
466
+ if (0 < missing.length) {
467
+ return { errors: missing.map((r) => rootFinding(r, relation, nodes)) };
468
+ }
469
+ named = [...new Set(roots)].sort(byLabel);
470
+ }
471
+ else {
472
+ // A root is a node nothing depends on. A SELF-EDGE does not make a
473
+ // node depended upon for this purpose: a module that names itself
474
+ // would otherwise stop being a root and take its whole subtree out
475
+ // of the drawing.
476
+ const depended = new Set(kept.filter((e) => e.to !== e.from).map((e) => e.to));
477
+ named = nodes.filter((n) => !depended.has(n)).sort(byLabel);
478
+ }
479
+ const out = [];
480
+ const rows = [];
481
+ const expanded = new Set();
482
+ const draw = (root) => {
483
+ if (0 < out.length) {
484
+ out.push('');
485
+ rows.push(null);
486
+ }
487
+ out.push(label(root));
488
+ rows.push({ depth: 0, text: label(root), mark: '', parent: rows.length });
489
+ expanded.add(root);
490
+ // ITERATIVE, with the ancestor chain carried as a set that is added
491
+ // to on the way down and removed from on the way up. A recursive
492
+ // walk is O(depth) stack frames and a deep dependency chain is a
493
+ // real shape, so the drawing of a model must not depend on how deep
494
+ // the interpreter lets it go.
495
+ const chain = new Set([root]);
496
+ const stack = [{ node: root, prefix: '', at: 0, row: rows.length - 1 }];
497
+ while (0 < stack.length) {
498
+ const frame = stack[stack.length - 1];
499
+ const list = kids.get(frame.node);
500
+ if (frame.at >= list.length) {
501
+ chain.delete(frame.node);
502
+ stack.pop();
503
+ continue;
504
+ }
505
+ const edge = list[frame.at++];
506
+ const last = frame.at === list.length;
507
+ const loop = chain.has(edge.to);
508
+ const seen = expanded.has(edge.to);
509
+ const grown = 0 < kids.get(edge.to).length;
510
+ const text = label(edge.to) + (many ? ' (' + edge.label + ')' : '');
511
+ const mark = loop ? ' (cycle)' : (seen && grown ? ' (*)' : '');
512
+ out.push(paint('rule', frame.prefix + (last ? '└── ' : '├── '))
513
+ + text + paint('repeat', mark));
514
+ rows.push({ depth: stack.length, text, mark, parent: frame.row });
515
+ if (loop || seen) {
516
+ continue;
517
+ }
518
+ expanded.add(edge.to);
519
+ chain.add(edge.to);
520
+ stack.push({
521
+ node: edge.to,
522
+ prefix: frame.prefix + (last ? ' ' : '│ '),
523
+ at: 0,
524
+ row: rows.length - 1,
525
+ });
526
+ }
527
+ };
528
+ for (const root of named) {
529
+ draw(root);
530
+ }
531
+ // EVERY NODE IS DRAWN. A component whose nodes all depend on each
532
+ // other has no node nothing depends on, so the derived roots miss it
533
+ // entirely -- and a graph with roots elsewhere would drop it in
534
+ // silence, which is the one thing a drawing must not do. The
535
+ // least-labelled node left is taken as a root of its own, until
536
+ // nothing is left. An explicitly named root is a request for one
537
+ // subtree and is left alone.
538
+ if (0 === roots.length) {
539
+ for (const n of nodes) {
540
+ if (!expanded.has(n)) {
541
+ draw(n);
542
+ }
543
+ }
544
+ }
545
+ return {
546
+ text: 'svg' === as
547
+ ? treeSvg(rows, `Dependency tree: ${nodes.length} nodes`, style)
548
+ : out.join('\n'),
549
+ };
550
+ }
551
+ // The tree as SVG: one line per row, each node indented one unit per
552
+ // depth, joined to its parent by a path that drops from the parent's
553
+ // row and turns in to the child. The marks are muted text after the
554
+ // label.
555
+ function treeSvg(rows, about, style) {
556
+ const U = 24;
557
+ const parts = [];
558
+ let width = 0;
559
+ rows.forEach((r, i) => {
560
+ if (null === r) {
561
+ return;
562
+ }
563
+ const y = i * LH;
564
+ const x = r.depth * U + 4;
565
+ if (0 < r.depth) {
566
+ const px = (r.depth - 1) * U + 8;
567
+ parts.push(svgPath(`M${px} ${r.parent * LH + LH}V${y + 10}H${x - 2}`, 'av-line'));
568
+ }
569
+ parts.push('' === r.mark
570
+ ? svgText(x, y + 14, 'av-t', r.text)
571
+ : `<text x="${x}" y="${y + 14}"><tspan class="av-t">${svgEsc(r.text)}` +
572
+ `</tspan><tspan class="av-m">${svgEsc(r.mark)}</tspan></text>`);
573
+ width = Math.max(width, x + (r.text.length + r.mark.length) * CH);
574
+ });
575
+ return svgDoc(width + PAD, rows.length * LH + PAD, about, parts, style);
576
+ }
577
+ // ---------------------------------------------------------------------
578
+ // The document tree
579
+ // THE SHAPE OF THE MODEL ITSELF, which no other kind draws. Every
580
+ // other figure here reads a REPORT -- the edge set, the provenance
581
+ // record, the subsumption order -- and so can only draw a document
582
+ // that has links, contributions or peers. A reader meeting a model for
583
+ // the first time wants the plainer thing first: what is in it, and how
584
+ // it is arranged.
585
+ //
586
+ // This is `get --keys --types` as a picture, and it reads the same
587
+ // walk: map keys in code-point order, list indices in order, and a
588
+ // leaf's KIND rather than its value -- the canon of a scalar's type,
589
+ // not the scalar. Values are what the document is for; the shape is
590
+ // what a reader needs before any of them mean anything.
591
+ //
592
+ // DEPTH IS A BOUND, NOT AN ELISION MARK. Below it the subtree is not
593
+ // drawn and the row says how many keys were not drawn, because a tree
594
+ // that stops without saying so is the one thing a structural drawing
595
+ // must not be.
596
+ const DEFAULT_DOC_DEPTH = 3;
597
+ // A node's own children, as the anchor walk sees them: map keys sorted
598
+ // by code point, list indices in order, and nothing for a leaf.
599
+ function docKids(v) {
600
+ const node = throughDoc(v);
601
+ if (true === node?.isMap) {
602
+ // AN ALIAS DECLARATION IS NOT PART OF THE DOCUMENT
603
+ // (docs/reference-language.md, "Aliases"): it does not generate
604
+ // and it does not appear in canon. It IS a key of the root map in
605
+ // the value tree, which `get --keys` reports and this does not --
606
+ // a figure of the document's shape that showed `%Cents` beside
607
+ // `customers` would be drawing the declaration as data
608
+ // (use-cases/BUGS.md 74).
609
+ return Object.keys(node.peg)
610
+ .filter((k) => !k.startsWith('%')).sort(keyorder_1.cmpCodePoint);
611
+ }
612
+ if (true === node?.isList) {
613
+ return Object.keys(node.peg).filter((k) => /^[0-9]+$/.test(k));
614
+ }
615
+ return [];
616
+ }
617
+ // A preference wraps its value without being a level of its own, and
618
+ // `anchorAt` already steps through a sizing residue; this is the same
619
+ // unwrapping, for the shape walk.
620
+ function throughDoc(v) {
621
+ // Every caller reaches this with a Val the anchor walk handed over,
622
+ // so the node is never absent and the optional chain that would say
623
+ // otherwise is an arm no test can take.
624
+ const node = (0, vet_1.throughResidue)(v);
625
+ return true === node.isPref ? throughDoc(node.peg) : node;
626
+ }
627
+ // What a leaf IS, in one short word: its canon, which for a constraint
628
+ // is the constraint and for a scalar its value. Long canons are cut,
629
+ // since the figure is the shape and not the data.
630
+ function docLeaf(v) {
631
+ // A CONTAINER WITH NOTHING IN IT IS NOT A LEAF, and calling it one
632
+ // by writing nothing after the key would make it read as a value the
633
+ // figure declined to describe. Its canon says what it is -- `{}`,
634
+ // `[]`, or a template a spread wrote and no member filled.
635
+ //
636
+ // `canon` is a string on every Val, so there is no other-type arm to
637
+ // take; the cut is the only decision here.
638
+ const canon = throughDoc(v).canon;
639
+ return 32 < canon.length ? canon.slice(0, 29) + '...' : canon;
640
+ }
641
+ function drawDoc(root, o, max, loss) {
642
+ const paint = painter(o.style);
643
+ const at = o.at ?? '$';
644
+ const anchor = (0, vet_1.anchorAt)(root, at);
645
+ if (null == anchor) {
646
+ return {
647
+ // The same code and the same sentence `get` answers with: the
648
+ // question is identical, so a caller that already handles one
649
+ // handles the other.
650
+ errors: [finding('no_path', 'reference', at, `The path ${at} names nothing in this document.`)],
651
+ };
652
+ }
653
+ const depth = o.depth ?? DEFAULT_DOC_DEPTH;
654
+ const out = [];
655
+ const rows = [];
656
+ let elided = 0;
657
+ out.push(at);
658
+ rows.push({ depth: 0, text: at, mark: '', parent: 0 });
659
+ const stack = [
660
+ { node: anchor, kids: docKids(anchor), at: 0, prefix: '', row: 0 },
661
+ ];
662
+ while (0 < stack.length) {
663
+ const frame = stack[stack.length - 1];
664
+ if (frame.at >= frame.kids.length) {
665
+ stack.pop();
666
+ continue;
667
+ }
668
+ const key = frame.kids[frame.at++];
669
+ const last = frame.at === frame.kids.length;
670
+ const child = throughDoc(throughDoc(frame.node).peg[key]);
671
+ const kids = docKids(child);
672
+ const under = stack.length < depth;
673
+ // A container the depth bound stops at says how many keys are not
674
+ // drawn; a leaf says what it is.
675
+ // A leaf says what it is and a stopped container says how many
676
+ // keys it holds; both are written after the key with one space,
677
+ // and neither is ever empty (a canon has at least one character).
678
+ const mark = 0 === kids.length ? ' ' + docLeaf(child)
679
+ : under ? '' : ` (${kids.length})`;
680
+ if (0 < kids.length && !under) {
681
+ elided += kids.length;
682
+ }
683
+ out.push(paint('rule', frame.prefix + (last ? '└── ' : '├── ')) + key +
684
+ paint('muted', mark));
685
+ rows.push({ depth: stack.length, text: key, mark, parent: frame.row });
686
+ if (max < rows.length) {
687
+ return {
688
+ errors: [rowsFinding(rows.length, max, '--at or --depth')],
689
+ };
690
+ }
691
+ if (0 < kids.length && under) {
692
+ stack.push({
693
+ node: child, kids, at: 0,
694
+ prefix: frame.prefix + (last ? ' ' : '│ '),
695
+ row: rows.length - 1,
696
+ });
697
+ }
698
+ }
699
+ if (0 < elided) {
700
+ loss.push({ code: 'depth_elided', count: elided });
701
+ }
702
+ return {
703
+ text: 'svg' === o.as
704
+ ? treeSvg(rows, `Document tree at ${at}: ${rows.length - 1} keys to depth ${depth}`, o.style)
705
+ : out.join('\n'),
706
+ };
707
+ }
708
+ // ---------------------------------------------------------------------
709
+ // The matrix (Ghoniem et al. 2004; Sangal et al. 2005)
710
+ // THE PARTITION ORDER: leaves first. Repeatedly take every unplaced
711
+ // node whose every successor is placed, in label order, as the next
712
+ // layer. That is a topological sort with a canonical tiebreak, and on
713
+ // an acyclic relation it yields a perfect lower triangle -- which IS
714
+ // the acyclicity proof, in the picture's own shape. Where nothing can
715
+ // be placed the relation has a cycle: the least unplaced node is
716
+ // placed alone, the strongly connected component it sits in is
717
+ // reported as `cycle_block`, and the walk continues -- the cycle's
718
+ // above-diagonal cell is then the acyclicity violation, drawn.
719
+ function partition(nodes, succ, reach, label, loss) {
720
+ const order = nodes.slice().sort((a, b) => (0, keyorder_1.cmpCodePoint)(label(a), label(b)));
721
+ const placed = new Set();
722
+ const out = [];
723
+ const blocks = [];
724
+ while (out.length < order.length) {
725
+ const ready = order.filter((n) => !placed.has(n) &&
726
+ succ.get(n).every((s) => s === n || placed.has(s)));
727
+ if (0 < ready.length) {
728
+ for (const n of ready) {
729
+ placed.add(n);
730
+ out.push(n);
731
+ }
732
+ continue;
733
+ }
734
+ const least = order.find((n) => !placed.has(n));
735
+ const scc = order.filter((n) => !placed.has(n) && (n === least ||
736
+ (reach.get(least).has(n) &&
737
+ reach.get(n).has(least))));
738
+ blocks.push(scc.map(label).join(' '));
739
+ placed.add(least);
740
+ out.push(least);
741
+ }
742
+ if (0 < blocks.length) {
743
+ loss.push({ code: 'cycle_block', count: blocks.length, detail: blocks });
744
+ }
745
+ return out;
746
+ }
747
+ // The relation a matrix draws: the one named, else the only one with
748
+ // edges, else a refusal -- a matrix over two predicates at once would
749
+ // draw a containment the model does not state.
750
+ function pickRelation(relation, keys) {
751
+ if (undefined !== relation) {
752
+ return keys.includes(relation) || 0 === keys.length
753
+ ? { relation } : { error: relationFinding(relation, keys) };
754
+ }
755
+ if (1 < keys.length) {
756
+ return {
757
+ error: finding('view_relation_ambiguous', 'reference', '$', 'The document has several relations with edges; ' +
758
+ 'name one with --relation.', 'relations with edges: ' + keys.join(', ')),
759
+ };
760
+ }
761
+ // No edges at all: no relation, and the empty name says so, as it
762
+ // does in the Go port.
763
+ return { relation: keys[0] ?? '' };
764
+ }
765
+ function drawMatrix(triples, decls, o, max, loss) {
766
+ const paint = painter(o.style);
767
+ const picked = pickRelation(o.relation, keysOf(triples));
768
+ if (undefined !== picked.error) {
769
+ return { errors: [picked.error] };
770
+ }
771
+ const relation = picked.relation;
772
+ const rel = triples.filter((e) => e.key === relation);
773
+ const nodes = nodesOf(rel);
774
+ if (max < nodes.length) {
775
+ return { errors: [rowsFinding(nodes.length, max, '--at or --relation')] };
776
+ }
777
+ const lab = labelsOf(nodes);
778
+ const label = (n) => lab.get(n);
779
+ const succ = new Map(nodes.map((n) => [n, []]));
780
+ const direct = new Set();
781
+ for (const e of rel) {
782
+ succ.get(e.from).push(e.to);
783
+ direct.add(e.from + SEP + e.to);
784
+ }
785
+ const reach = reachOf(nodes, succ);
786
+ // The `unmirrored` mark: an edge under a predicate that declares
787
+ // `inverse(n)` whose mirror is absent from the full edge set. The
788
+ // matrix shows in one glyph what `aontu relations` reports as
789
+ // `relation_inverse_missing`, and both read one edge set.
790
+ const inverses = [...(decls.get(relation)?.inverses ?? [])];
791
+ const mirrored = (from, to) => 0 === inverses.length || triples.some((e) => e.from === to && e.to === from && inverses.includes(e.key));
792
+ const order = 'partition' === o.order
793
+ ? partition(nodes, succ, reach, label, loss)
794
+ : nodes.slice().sort((a, b) => (0, keyorder_1.cmpCodePoint)(label(a), label(b)));
795
+ const idx = order.map((_, i) => String(i + 1));
796
+ const iw = widest(idx);
797
+ const w = widest(order.map(label));
798
+ const lines = [];
799
+ // The index header, one line per digit when the count needs more
800
+ // than one: the digits stack, most significant line first, so every
801
+ // column stays one character wide.
802
+ for (let d = 0; d < iw; d++) {
803
+ lines.push(' '.repeat(w + 1 + iw + 1) +
804
+ paint('muted', idx.map((s) => lpad(s, iw)[d]).join(' ')));
805
+ }
806
+ let above = 0;
807
+ const grid = [];
808
+ order.forEach((r, ri) => {
809
+ const cells = order.map((c, ci) => {
810
+ const isDirect = direct.has(r + SEP + c);
811
+ if (isDirect && ci > ri) {
812
+ above++;
813
+ }
814
+ // A SELF-DEPENDENCY is drawn on the diagonal rather than hidden
815
+ // by it: it is the shortest cycle a model can have, and exactly
816
+ // the fact a dependency matrix is read for.
817
+ return isDirect ? (mirrored(r, c) ? 'X' : '!')
818
+ : ri === ci ? '\\'
819
+ : o.closure && reach.get(r).has(c) ? '+' : '.';
820
+ });
821
+ grid.push(cells);
822
+ lines.push(pad(label(r), w) + ' ' + paint('muted', lpad(idx[ri], iw)) + ' ' +
823
+ cells.map((g) => paint(CELL_ROLE[g], g)).join(' '));
824
+ });
825
+ const footer = `# above-diagonal direct cells: ${above}`;
826
+ lines.push(paint('muted', footer));
827
+ if ('svg' === o.as) {
828
+ return {
829
+ text: matrixSvg(order.map(label), idx, grid, footer, `Dependency matrix${over(relation)}: ${order.length} rows, ` +
830
+ `${above} direct cells above the diagonal`, o.style),
831
+ };
832
+ }
833
+ return { text: lines.join('\n') };
834
+ }
835
+ // The matrix as SVG: the same glyph grid as cells, each a square whose
836
+ // class is its state, the diagonal drawn as a line through its cell.
837
+ const CELL_CLASS = {
838
+ X: 'av-direct', '!': 'av-unmirrored', '+': 'av-closure',
839
+ '.': 'av-cell', '\\': 'av-cell',
840
+ };
841
+ // The same five states as ROLES, for the text profile. One table per
842
+ // mechanism rather than one shared one, because the two vocabularies
843
+ // are not in step: SVG needs a class for the empty cell (it draws a
844
+ // rect there) and the text profile has nothing to say about a `.`
845
+ // beyond that it is not a mark.
846
+ const CELL_ROLE = {
847
+ X: 'direct', '!': 'unmirrored', '+': 'closure',
848
+ '.': 'muted', '\\': 'rule',
849
+ };
850
+ function matrixSvg(labels, idx, grid, footer, about, style) {
851
+ const S = 20;
852
+ const w = widest(labels);
853
+ const iw = widest(idx);
854
+ const gutter = w * CH + 8 + iw * CH + 8;
855
+ const y0 = LH + 4;
856
+ const parts = [];
857
+ idx.forEach((s, c) => {
858
+ parts.push(svgText(gutter + c * S + 10, 14, 'av-m', s, 'middle'));
859
+ });
860
+ labels.forEach((l, r) => {
861
+ const y = y0 + r * S;
862
+ parts.push(svgText(4, y + 14, 'av-t', l));
863
+ parts.push(svgText(gutter - 8, y + 14, 'av-m', idx[r], 'end'));
864
+ grid[r].forEach((g, c) => {
865
+ const x = gutter + c * S;
866
+ parts.push(svgRect(x, y, S, S, CELL_CLASS[g]));
867
+ if ('\\' === g) {
868
+ parts.push(svgPath(`M${x} ${y}L${x + S} ${y + S}`, 'av-line'));
869
+ }
870
+ });
871
+ });
872
+ const n = labels.length;
873
+ parts.push(svgText(4, y0 + n * S + 16, 'av-m', footer));
874
+ const width = Math.max(gutter + n * S, 4 + footer.length * CH) + PAD;
875
+ return svgDoc(width, y0 + n * S + LH + PAD, about, parts, style);
876
+ }
877
+ // A node's field, as label text: the value of a scalar leaf at
878
+ // `path.field`, taken as its canon for anything but a string. A value
879
+ // the document leaves open is `unresolved_field` rather than an error.
880
+ function fieldOf(root, path, field) {
881
+ const v = (0, vet_1.anchorAt)(root, path + '.' + field);
882
+ if (null == v || true !== v.isVal) {
883
+ return undefined;
884
+ }
885
+ if ('string' === typeof v.peg) {
886
+ return v.peg;
887
+ }
888
+ return true === v.isScalar ? v.canon : undefined;
889
+ }
890
+ function drawGraph(triples, decls, root, o, max, loss) {
891
+ const keys = keysOf(triples);
892
+ for (const r of o.relations) {
893
+ if (!keys.includes(r)) {
894
+ return { errors: [relationFinding(r, keys)] };
895
+ }
896
+ }
897
+ const kept = 0 === o.relations.length
898
+ ? triples : triples.filter((e) => o.relations.includes(e.key));
899
+ // INVERSE SUPPRESSION: a hand-maintained mirror under a declared
900
+ // `inverse(n)` is one fact drawn twice, so the mirror half is not
901
+ // drawn and the count is reported. The declaring direction wins.
902
+ const declared = (key, mirror) => true === decls.get(key)?.inverses.has(mirror);
903
+ const edges = [];
904
+ let suppressed = 0;
905
+ for (const e of kept) {
906
+ const mirror = kept.some((m) => m.from === e.to && m.to === e.from && declared(m.key, e.key));
907
+ if (mirror) {
908
+ suppressed++;
909
+ }
910
+ else {
911
+ edges.push(e);
912
+ }
913
+ }
914
+ if (0 < suppressed) {
915
+ loss.push({ code: 'inverse_suppressed', count: suppressed });
916
+ }
917
+ const paths = nodesOf(edges);
918
+ if (max < paths.length) {
919
+ return { errors: [rowsFinding(paths.length, max, '--at or --relation')] };
920
+ }
921
+ const lab = labelsOf(paths);
922
+ // `--group-by` and `--label` read a field of each node; a node
923
+ // without a value there is counted, and drawn ungrouped or under
924
+ // its path.
925
+ const unresolved = [];
926
+ const nodes = paths.map((p) => {
927
+ const short = lab.get(p);
928
+ const node = { path: p, label: short, id: ident(short) };
929
+ if (undefined !== o.groupBy) {
930
+ const g = fieldOf(root, p, o.groupBy);
931
+ if (undefined === g) {
932
+ unresolved.push(p + '.' + o.groupBy);
933
+ }
934
+ else {
935
+ node.group = g;
936
+ }
937
+ }
938
+ if (undefined !== o.label) {
939
+ const l = fieldOf(root, p, o.label);
940
+ if (undefined === l) {
941
+ unresolved.push(p + '.' + o.label);
942
+ }
943
+ else {
944
+ node.label = l;
945
+ }
946
+ }
947
+ return node;
948
+ });
949
+ if (0 < unresolved.length) {
950
+ loss.push({
951
+ code: 'unresolved_field', count: unresolved.length,
952
+ detail: unresolved.sort(keyorder_1.cmpCodePoint),
953
+ });
954
+ }
955
+ for (const n of nodes) {
956
+ if (hasLineBreak(n.label) || hasLineBreak(n.group ?? '')) {
957
+ return { errors: [lineBreakFinding(n.path)] };
958
+ }
959
+ }
960
+ // Groups in label order, ids ordinal; nodes within a group, and the
961
+ // ungrouped after them, in label order. That order is the emitted
962
+ // order, and the crossing count is a property of it.
963
+ const groups = [...new Set(nodes.filter((n) => undefined !== n.group)
964
+ .map((n) => n.group))].sort(keyorder_1.cmpCodePoint);
965
+ const byLabel = (a, b) => (0, keyorder_1.cmpCodePoint)(a.label, b.label) || (0, keyorder_1.cmpCodePoint)(a.path, b.path);
966
+ const emitted = [];
967
+ for (const g of groups) {
968
+ emitted.push(...nodes.filter((n) => n.group === g).sort(byLabel));
969
+ }
970
+ const loose = nodes.filter((n) => undefined === n.group).sort(byLabel);
971
+ emitted.push(...loose);
972
+ const byPath = new Map(nodes.map((n) => [n.path, n]));
973
+ const node = (p) => byPath.get(p);
974
+ const at = new Map(emitted.map((n, i) => [n.path, i]));
975
+ const drawn = edges.slice().sort((a, b) => (0, keyorder_1.cmpCodePoint)(node(a.from).label, node(b.from).label)
976
+ || (0, keyorder_1.cmpCodePoint)(node(a.to).label, node(b.to).label)
977
+ || (0, keyorder_1.cmpCodePoint)(a.key, b.key));
978
+ // Crossings in the emitted order: two edges cross when their spans
979
+ // interleave. A count, not a layout -- the consumer lays the picture
980
+ // out, and this says how tangled the order it is handed is.
981
+ let crossings = 0;
982
+ const span = (e) => {
983
+ const a = at.get(e.from);
984
+ const b = at.get(e.to);
985
+ return a < b ? [a, b] : [b, a];
986
+ };
987
+ for (let i = 0; i < drawn.length; i++) {
988
+ for (let j = i + 1; j < drawn.length; j++) {
989
+ const [a1, b1] = span(drawn[i]);
990
+ const [a2, b2] = span(drawn[j]);
991
+ if ((a1 < a2 && a2 < b1 && b1 < b2) || (a2 < a1 && a1 < b2 && b2 < b1)) {
992
+ crossings++;
993
+ }
994
+ }
995
+ }
996
+ if (0 < crossings) {
997
+ loss.push({ code: 'crossings', count: crossings });
998
+ }
999
+ const id = (p) => node(p).id;
1000
+ const out = [];
1001
+ if ('mermaid' === o.as) {
1002
+ const esc = (s) => escape(s, MERMAID_ESC);
1003
+ out.push('flowchart LR');
1004
+ groups.forEach((g, gi) => {
1005
+ out.push(` subgraph g${gi}["${esc(g)}"]`);
1006
+ for (const n of emitted.filter((n) => n.group === g)) {
1007
+ out.push(` ${n.id}["${esc(n.label)}"]`);
1008
+ }
1009
+ out.push(' end');
1010
+ });
1011
+ for (const n of loose) {
1012
+ out.push(` ${n.id}["${esc(n.label)}"]`);
1013
+ }
1014
+ for (const e of drawn) {
1015
+ out.push(` ${id(e.from)} -->|"${esc(e.key)}"| ${id(e.to)}`);
1016
+ }
1017
+ }
1018
+ else if ('dot' === o.as) {
1019
+ const esc = (s) => escape(s, DOT_ESC);
1020
+ out.push('digraph G {', ' rankdir=LR;', ' node [shape=box];');
1021
+ groups.forEach((g, gi) => {
1022
+ out.push(` subgraph cluster_g${gi} {`, ` label="${esc(g)}";`);
1023
+ for (const n of emitted.filter((n) => n.group === g)) {
1024
+ out.push(` ${n.id} [label="${esc(n.label)}"];`);
1025
+ }
1026
+ out.push(' }');
1027
+ });
1028
+ for (const n of loose) {
1029
+ out.push(` ${n.id} [label="${esc(n.label)}"];`);
1030
+ }
1031
+ for (const e of drawn) {
1032
+ out.push(` ${id(e.from)} -> ${id(e.to)} [label="${esc(e.key)}"];`);
1033
+ }
1034
+ out.push('}');
1035
+ }
1036
+ else {
1037
+ // Entity relationships, as Mermaid's own erDiagram. Cardinality is
1038
+ // not something the model states, so every relationship is drawn
1039
+ // many-to-many and the label carries the predicate: drawing a
1040
+ // cardinality the model does not assert would be an invention. An
1041
+ // erDiagram has no separate label -- the identifier IS what the
1042
+ // reader sees -- so it is the encoded label, unique by the label
1043
+ // rule. Every node is in some relationship, since the node set is
1044
+ // what the edges connect.
1045
+ const esc = (s) => escape(s, MERMAID_ESC);
1046
+ out.push('erDiagram');
1047
+ for (const e of drawn) {
1048
+ out.push(` ${id(e.from)} }o--o{ ${id(e.to)} : "${esc(e.key)}"`);
1049
+ }
1050
+ }
1051
+ return { text: out.join('\n') };
1052
+ }
1053
+ // THE LAYER DIAGRAM every architecture document has a hand-drawn
1054
+ // version of: one band per layer, the layers stacked with the one
1055
+ // nothing depends on at the top, each module in its band, and the
1056
+ // rule -- dependencies point DOWN -- read off the bands. The band a
1057
+ // node belongs to is the value of `--group-by`; the order of the
1058
+ // bands is DERIVED from the relation, as the partition order over the
1059
+ // layer-level graph (a layer depends on the layers its modules depend
1060
+ // on), so it is a function of the model and not of a list somebody has
1061
+ // to keep in step with it -- unless the model has an upward edge, when
1062
+ // the layer graph is cyclic and no order is derivable, which is what
1063
+ // `--layers` (top first) is for. A sideways edge (within one band) is
1064
+ // ordinary engineering and counted; an UPWARD edge is the violation
1065
+ // the drawing exists to show, and is named under the figure.
1066
+ function drawLayer(triples, root, o, max, loss) {
1067
+ if (undefined === o.groupBy) {
1068
+ return {
1069
+ errors: [finding('view_group_required', 'reference', '$', 'The layer diagram needs the field that names each node\'s layer; ' +
1070
+ 'name it with --group-by.')],
1071
+ };
1072
+ }
1073
+ const picked = pickRelation(o.relation, keysOf(triples));
1074
+ if (undefined !== picked.error) {
1075
+ return { errors: [picked.error] };
1076
+ }
1077
+ const relation = picked.relation;
1078
+ const rel = triples.filter((e) => e.key === relation);
1079
+ const paths = nodesOf(rel);
1080
+ if (max < paths.length) {
1081
+ return { errors: [rowsFinding(paths.length, max, '--at or --relation')] };
1082
+ }
1083
+ const lab = labelsOf(paths);
1084
+ // A node whose layer field is unresolved is counted and drawn in a
1085
+ // band of its own at the bottom, named `-`.
1086
+ const unresolved = [];
1087
+ const nodes = paths.map((p) => {
1088
+ const short = lab.get(p);
1089
+ const g = fieldOf(root, p, o.groupBy);
1090
+ if (undefined === g) {
1091
+ unresolved.push(p + '.' + o.groupBy);
1092
+ }
1093
+ return { path: p, label: short, id: ident(short), group: g ?? '-' };
1094
+ });
1095
+ if (0 < unresolved.length) {
1096
+ loss.push({
1097
+ code: 'unresolved_field', count: unresolved.length,
1098
+ detail: unresolved.sort(keyorder_1.cmpCodePoint),
1099
+ });
1100
+ }
1101
+ for (const n of nodes) {
1102
+ if (hasLineBreak(n.group)) {
1103
+ return { errors: [lineBreakFinding(n.path)] };
1104
+ }
1105
+ }
1106
+ const byPath = new Map(nodes.map((n) => [n.path, n]));
1107
+ const node = (p) => byPath.get(p);
1108
+ // The layer-level graph, and its partition order: leaves first, so
1109
+ // the band nothing depends on is placed LAST and drawn at the top.
1110
+ const names = [...new Set(nodes.map((n) => n.group))]
1111
+ .filter((g) => '-' !== g).sort(keyorder_1.cmpCodePoint);
1112
+ const succ = new Map(names.map((g) => [g, []]));
1113
+ for (const e of rel) {
1114
+ const from = node(e.from).group;
1115
+ const to = node(e.to).group;
1116
+ if (from !== to && '-' !== from && '-' !== to
1117
+ && !o.layers.includes(from) && !o.layers.includes(to)) {
1118
+ succ.get(from).push(to);
1119
+ }
1120
+ }
1121
+ // Named bands first, in the order given; the rest derived, and the
1122
+ // unresolved band last.
1123
+ const given = o.layers.filter((g) => names.includes(g));
1124
+ const rest = names.filter((g) => !given.includes(g));
1125
+ const same = (g) => g;
1126
+ const order = given.concat(partition(rest, succ, reachOf(rest, succ), same, loss).reverse());
1127
+ if (nodes.some((n) => '-' === n.group)) {
1128
+ order.push('-');
1129
+ }
1130
+ // Labels are unique in a drawing, so they order a band on their own.
1131
+ const bands = order.map((name) => ({
1132
+ name,
1133
+ nodes: nodes.filter((n) => n.group === name).sort((a, b) => (0, keyorder_1.cmpCodePoint)(a.label, b.label)),
1134
+ }));
1135
+ const level = new Map(order.map((g, i) => [g, i]));
1136
+ // Every edge is downward, sideways or upward by the bands it joins.
1137
+ const drawn = rel.slice().sort((a, b) => (0, keyorder_1.cmpCodePoint)(node(a.from).label, node(b.from).label)
1138
+ || (0, keyorder_1.cmpCodePoint)(node(a.to).label, node(b.to).label));
1139
+ let down = 0;
1140
+ let side = 0;
1141
+ const classed = drawn.map((e) => {
1142
+ const fi = level.get(node(e.from).group);
1143
+ const ti = level.get(node(e.to).group);
1144
+ if (fi < ti) {
1145
+ down++;
1146
+ return { edge: e, way: 'downward' };
1147
+ }
1148
+ if (fi === ti) {
1149
+ side++;
1150
+ return { edge: e, way: 'sideways' };
1151
+ }
1152
+ return { edge: e, way: 'upward' };
1153
+ });
1154
+ const upward = classed.filter((c) => 'upward' === c.way).length;
1155
+ // WHICH EDGES ARE SHOWN. Mermaid lays edges out itself and drew every
1156
+ // one before this option existed; the fixed grids drew the upward
1157
+ // ones, which are the violations the bands cannot show on their own.
1158
+ const edges = o.edges ?? ('mermaid' === o.as ? 'all' : 'upward');
1159
+ const shown = 'all' === edges ? classed
1160
+ : 'none' === edges ? []
1161
+ : classed.filter((c) => 'upward' === c.way);
1162
+ // A document with no edges has no relation to count under; the
1163
+ // footer names the absence as the panels do.
1164
+ const footer = [`# ${'' === relation ? '-' : relation}: ${down} downward, ` +
1165
+ `${side} sideways, ${upward} upward`];
1166
+ for (const c of shown) {
1167
+ footer.push(`# ${c.way}: ${node(c.edge.from).label} -> ` +
1168
+ `${node(c.edge.to).label}`);
1169
+ }
1170
+ const out = [];
1171
+ if ('svg' === o.as) {
1172
+ // The description says WHAT WAS DRAWN, because two layer figures of
1173
+ // one model on one page differ by exactly that, and a reader who
1174
+ // cannot see them has only this to tell them apart.
1175
+ const drew = 'all' === edges
1176
+ ? `${shown.length} edges drawn, ${upward} of them upward`
1177
+ : 'none' === edges
1178
+ ? `${upward} upward edges, none drawn`
1179
+ : `${upward} upward edges`;
1180
+ return {
1181
+ text: layerSvg(bands, shown, footer, `Architecture layers${over(relation)}: ${bands.length} bands, ${drew}`, o.style),
1182
+ };
1183
+ }
1184
+ if ('text' === o.as) {
1185
+ const paint = painter(o.style);
1186
+ const w = widest(bands.map((b) => b.name));
1187
+ const rows = bands.map((b) => paint('muted', pad(b.name, w)) + ' ' +
1188
+ b.nodes.map((n) => n.label).join(' '));
1189
+ const inner = widest(bands.map((b) => pad(b.name, w) + ' ' + b.nodes.map((n) => n.label).join(' ')));
1190
+ const rule = paint('rule', '+' + '-'.repeat(inner + 2) + '+');
1191
+ out.push(rule);
1192
+ rows.forEach((row, i) => {
1193
+ // The row was padded from its UNPAINTED width, which the band
1194
+ // name's escapes do not change; `pad` would count them, so the
1195
+ // padding is computed here and appended.
1196
+ const bare = pad(bands[i].name, w) + ' ' +
1197
+ bands[i].nodes.map((n) => n.label).join(' ');
1198
+ out.push(paint('rule', '|') + ' ' + row +
1199
+ ' '.repeat(inner - bare.length) + ' ' + paint('rule', '|'), rule);
1200
+ });
1201
+ // The first footer line counts; the rest name one edge each, and
1202
+ // an upward edge is the violation the bands cannot show.
1203
+ out.push(paint('muted', footer[0]));
1204
+ footer.slice(1).forEach((f, i) => {
1205
+ out.push(paint('upward' === shown[i].way ? 'upward' : 'muted', f));
1206
+ });
1207
+ }
1208
+ else {
1209
+ const esc = (s) => escape(s, MERMAID_ESC);
1210
+ out.push('flowchart TB');
1211
+ bands.forEach((b, i) => {
1212
+ out.push(` subgraph g${i}["${esc(b.name)}"]`, ' direction LR');
1213
+ for (const n of b.nodes) {
1214
+ out.push(` ${n.id}["${esc(n.label)}"]`);
1215
+ }
1216
+ out.push(' end');
1217
+ });
1218
+ for (const c of shown) {
1219
+ out.push('upward' === c.way
1220
+ ? ` ${node(c.edge.from).id} -.->|"upward"| ${node(c.edge.to).id}`
1221
+ : ` ${node(c.edge.from).id} --> ${node(c.edge.to).id}`);
1222
+ }
1223
+ }
1224
+ return { text: out.join('\n') };
1225
+ }
1226
+ // The layers as SVG: one band per row, its modules as boxes laid left
1227
+ // to right, and every SHOWN edge drawn between them -- an upward one
1228
+ // dashed and alert-coloured, because it is the violation the bands
1229
+ // cannot show on their own; a downward one straight down from the
1230
+ // bottom of its box to the top of the one it names; a sideways one
1231
+ // dipped below the boxes, since two modules of one band sit on the
1232
+ // same line and a straight edge between them would cross whatever
1233
+ // stands between.
1234
+ function layerSvg(bands, shown, footer, about, style) {
1235
+ const BH = 44;
1236
+ const gutter = widest(bands.map((b) => b.name)) * CH + 16;
1237
+ const box = new Map();
1238
+ let width = 0;
1239
+ bands.forEach((b, i) => {
1240
+ let x = gutter;
1241
+ for (const n of b.nodes) {
1242
+ const w = n.label.length * CH + 12;
1243
+ box.set(n.path, { x, y: 4 + i * BH + 10, w });
1244
+ x += w + 10;
1245
+ }
1246
+ width = Math.max(width, x - 10);
1247
+ });
1248
+ for (const f of footer) {
1249
+ width = Math.max(width, 4 + f.length * CH);
1250
+ }
1251
+ width += PAD;
1252
+ const parts = [];
1253
+ bands.forEach((b, i) => {
1254
+ const y = 4 + i * BH;
1255
+ parts.push(svgRect(4, y, width - 8, BH, 'av-cell'));
1256
+ parts.push(svgText(12, y + 27, 'av-m', b.name));
1257
+ for (const n of b.nodes) {
1258
+ const at = box.get(n.path);
1259
+ parts.push(svgRect(at.x, at.y, at.w, 24, 'av-box'));
1260
+ parts.push(svgText(at.x + 6, at.y + 16, 'av-t', n.label));
1261
+ }
1262
+ });
1263
+ if (0 < shown.length) {
1264
+ parts.push('<defs>' +
1265
+ '<marker id="av-arrow" viewBox="0 0 8 8" refX="8" refY="4" ' +
1266
+ 'markerWidth="8" markerHeight="8" orient="auto">' +
1267
+ '<path d="M0 0L8 4L0 8Z" fill="var(--av-alert,#d1242f)"/></marker>' +
1268
+ '<marker id="av-tip" viewBox="0 0 8 8" refX="8" refY="4" ' +
1269
+ 'markerWidth="8" markerHeight="8" orient="auto">' +
1270
+ '<path d="M0 0L8 4L0 8Z" fill="var(--av-rule,#8c959f)"/></marker>' +
1271
+ '</defs>');
1272
+ }
1273
+ for (const c of shown) {
1274
+ const from = box.get(c.edge.from);
1275
+ const to = box.get(c.edge.to);
1276
+ const fx = from.x + Math.floor(from.w / 2);
1277
+ const tx = to.x + Math.floor(to.w / 2);
1278
+ if ('upward' === c.way) {
1279
+ parts.push(`<path d="M${fx} ${from.y}L${tx} ${to.y + 24}" ` +
1280
+ 'class="av-up" marker-end="url(#av-arrow)"/>');
1281
+ }
1282
+ else if ('downward' === c.way) {
1283
+ parts.push(`<path d="M${fx} ${from.y + 24}L${tx} ${to.y}" ` +
1284
+ 'class="av-line" marker-end="url(#av-tip)"/>');
1285
+ }
1286
+ else {
1287
+ // Below the boxes and back up, staying inside the band.
1288
+ const y = from.y + 24;
1289
+ parts.push(`<path d="M${fx} ${y}V${y + 6}H${tx}V${y}" ` +
1290
+ 'class="av-line" marker-end="url(#av-tip)"/>');
1291
+ }
1292
+ }
1293
+ const y1 = 4 + bands.length * BH + 4;
1294
+ footer.forEach((f, i) => {
1295
+ parts.push(svgText(4, y1 + i * LH + 14, 'av-m', f));
1296
+ });
1297
+ return svgDoc(width, y1 + footer.length * LH + PAD, about, parts, style);
1298
+ }
1299
+ // Elements grouped by their exact membership signature; columns by
1300
+ // degree descending, then cardinality descending, then signature (the
1301
+ // names of the sets it lies in) in code-point order. Elements within a
1302
+ // column in code-point order.
1303
+ function columnsOf(names, members, elements, shown) {
1304
+ const groups = new Map();
1305
+ const sorted = elements.slice().sort((a, b) => (0, keyorder_1.cmpCodePoint)(shown(a), shown(b)));
1306
+ for (const el of sorted) {
1307
+ const sig = names.map((n) => members.get(n).has(el));
1308
+ const key = sig.map((b) => b ? '1' : '0').join('');
1309
+ const col = groups.get(key);
1310
+ if (undefined === col) {
1311
+ groups.set(key, { sig, items: [shown(el)] });
1312
+ }
1313
+ else {
1314
+ col.items.push(shown(el));
1315
+ }
1316
+ }
1317
+ const degree = (c) => c.sig.filter((b) => b).length;
1318
+ const sigText = (c) => names.filter((_n, i) => c.sig[i]).join(' ');
1319
+ return [...groups.values()].sort((a, b) => degree(b) - degree(a) || b.items.length - a.items.length
1320
+ || (0, keyorder_1.cmpCodePoint)(sigText(a), sigText(b)));
1321
+ }
1322
+ function renderPanel(p, style) {
1323
+ const paint = painter(style);
1324
+ const w = widest(p.names);
1325
+ const out = [paint('muted', p.header), ''];
1326
+ const most = p.sizes.reduce((m, n) => Math.max(m, n), 0);
1327
+ p.names.forEach((n, i) => {
1328
+ // The bar is padded to `most` from its own length, so the pad is
1329
+ // written outside the painted run rather than counted inside it.
1330
+ const bar = '#'.repeat(p.sizes[i]);
1331
+ out.push(pad(n, w) + ' ' +
1332
+ (p.bars ? paint('bar', bar) + ' '.repeat(most - bar.length) + ' ' : '') +
1333
+ paint('muted', String(p.sizes[i])));
1334
+ });
1335
+ out.push('');
1336
+ p.names.forEach((n, i) => {
1337
+ out.push(pad(n, w) + ' ' + paint('rule', '|') + ' ' +
1338
+ p.cols.map((c) => c.sig[i] ? paint('direct', '*') : paint('hole', '.'))
1339
+ .join(' '));
1340
+ });
1341
+ out.push(pad('', w) + ' ' + paint('rule', '+' + '-'.repeat(2 * p.cols.length)));
1342
+ if (p.bars) {
1343
+ const tallest = p.cols.reduce((m, c) => Math.max(m, c.items.length), 0);
1344
+ // The bars, tallest column first; a line ends at its last bar. The
1345
+ // trailing blanks are trimmed BEFORE painting, so an escape can
1346
+ // never be what the trim leaves behind.
1347
+ for (let h = tallest; 0 < h; h--) {
1348
+ const cells = p.cols.map((c) => h <= c.items.length ? ' #' : ' ')
1349
+ .join('').replace(/ +$/, '');
1350
+ out.push(pad('', w) + ' ' + paint('rule', '|') +
1351
+ cells.replace(/#/g, () => paint('bar', '#')));
1352
+ }
1353
+ }
1354
+ out.push(pad('', w) + ' ' +
1355
+ paint('muted', p.cols.map((c) => String(c.items.length)).join(' ')));
1356
+ out.push('');
1357
+ p.cols.forEach((c, i) => {
1358
+ const shown = 4 < c.items.length && !p.bars
1359
+ ? c.items.slice(0, 3).join(' ') + ' ...' : c.items.join(' ');
1360
+ out.push(paint('muted', ` col ${i + 1}${p.bars ? '' : ` (${c.items.length})`}:`) +
1361
+ ` ${shown}` + (c.sig.some((b) => b) ? '' : paint('muted', p.none)));
1362
+ });
1363
+ return out.join('\n');
1364
+ }
1365
+ // The panel as SVG: the set sizes as bars, the intersections as a dot
1366
+ // matrix (a filled dot where the set lies in the column), the column
1367
+ // cardinalities as bars under it, and the columns' elements as text.
1368
+ function panelSvg(p, about, style) {
1369
+ const w = widest(p.names);
1370
+ const most = p.sizes.reduce((m, n) => Math.max(m, n), 0);
1371
+ const parts = [svgText(4, 14, 'av-m', p.header)];
1372
+ const gx = w * CH + 8;
1373
+ const yS = LH + 8;
1374
+ p.names.forEach((n, i) => {
1375
+ const y = yS + i * LH;
1376
+ parts.push(svgText(4, y + 14, 'av-t', n));
1377
+ if (p.bars) {
1378
+ parts.push(svgRect(gx, y + 3, p.sizes[i] * 10, 14, 'av-bar'));
1379
+ }
1380
+ parts.push(svgText(gx + (p.bars ? most * 10 + 8 : 0), y + 14, 'av-m', String(p.sizes[i])));
1381
+ });
1382
+ const yM = yS + p.names.length * LH + 8;
1383
+ p.names.forEach((n, i) => {
1384
+ parts.push(svgText(4, yM + i * LH + 14, 'av-t', n));
1385
+ p.cols.forEach((c, ci) => {
1386
+ parts.push(`<circle cx="${gx + ci * 20 + 10}" cy="${yM + i * LH + 10}" r="5" ` +
1387
+ `class="${c.sig[i] ? 'av-dot' : 'av-hole'}"/>`);
1388
+ });
1389
+ });
1390
+ const yB = yM + p.names.length * LH + 4;
1391
+ const tallest = p.cols.reduce((m, c) => Math.max(m, c.items.length), 0);
1392
+ parts.push(svgPath(`M${gx} ${yB}H${gx + p.cols.length * 20}`, 'av-line'));
1393
+ p.cols.forEach((c, ci) => {
1394
+ parts.push(svgRect(gx + ci * 20 + 4, yB, 12, c.items.length * 8, 'av-bar'));
1395
+ parts.push(svgText(gx + ci * 20 + 10, yB + tallest * 8 + 14, 'av-m', String(c.items.length), 'middle'));
1396
+ });
1397
+ const yI = yB + tallest * 8 + LH + 4;
1398
+ const lines = [];
1399
+ p.cols.forEach((c, i) => {
1400
+ const shown = 4 < c.items.length && !p.bars
1401
+ ? c.items.slice(0, 3).join(' ') + ' ...' : c.items.join(' ');
1402
+ lines.push(`col ${i + 1}${p.bars ? '' : ` (${c.items.length})`}: ${shown}` +
1403
+ (c.sig.some((b) => b) ? '' : p.none));
1404
+ });
1405
+ lines.forEach((l, i) => {
1406
+ parts.push(svgText(4, yI + i * LH + 14, 'av-t', l));
1407
+ });
1408
+ const width = Math.max(gx + p.cols.length * 20, gx + (p.bars ? most * 10 + 8 : 0) + 3 * CH, 4 + widest(lines) * CH, 4 + p.header.length * CH) + PAD;
1409
+ return svgDoc(width, yI + lines.length * LH + PAD, about, parts, style);
1410
+ }
1411
+ // Elide the columns beyond `--max-cols`, counted. Zero means no limit,
1412
+ // in both ports.
1413
+ function elide(cols, maxCols, loss) {
1414
+ if (undefined === maxCols || 0 === maxCols || cols.length <= maxCols) {
1415
+ return cols;
1416
+ }
1417
+ loss.push({ code: 'cols_elided', count: cols.length - maxCols });
1418
+ return cols.slice(0, maxCols);
1419
+ }
1420
+ // The generated value at a path, walked plainly: the panel reads
1421
+ // `generate()`, never the Val tree.
1422
+ function genAt(gen, path) {
1423
+ let v = gen;
1424
+ for (const part of (0, query_1.pathParts)(path)) {
1425
+ if (null == v || 'object' !== typeof v) {
1426
+ return undefined;
1427
+ }
1428
+ v = v[part];
1429
+ }
1430
+ return v;
1431
+ }
1432
+ function shapeFinding(path, message) {
1433
+ return finding('view_sets_shape', 'reference', path, message);
1434
+ }
1435
+ const allStrings = (xs) => xs.every((x) => 'string' === typeof x);
1436
+ function drawSets(gen, o, max, loss) {
1437
+ const family = genAt(gen, o.sets);
1438
+ if (null == family || 'object' !== typeof family || Array.isArray(family)) {
1439
+ return { errors: [shapeFinding(o.sets, 'The set family is not a map.')] };
1440
+ }
1441
+ const names = Object.keys(family).sort(keyorder_1.cmpCodePoint);
1442
+ if (max < names.length) {
1443
+ return { errors: [rowsFinding(names.length, max, '--sets')] };
1444
+ }
1445
+ const members = new Map();
1446
+ const elements = new Set();
1447
+ for (const n of names) {
1448
+ const list = family[n]?.[o.member];
1449
+ if (!Array.isArray(list) || !allStrings(list)) {
1450
+ return {
1451
+ errors: [shapeFinding(`${o.sets}.${n}.${o.member}`, 'A set\'s members must be a list of strings.')],
1452
+ };
1453
+ }
1454
+ members.set(n, new Set(list));
1455
+ for (const x of list) {
1456
+ elements.add(x);
1457
+ }
1458
+ }
1459
+ if (undefined !== o.universe) {
1460
+ // A universe MAP names its elements by ADDRESS -- `$.permissions`
1461
+ // holds `$.permissions.admin_all` -- which is what a member written
1462
+ // `path($.permissions.admin_all)` generates, so the two meet on the
1463
+ // path; a universe list names them as it lists them.
1464
+ const u = genAt(gen, o.universe);
1465
+ const all = Array.isArray(u) ? u
1466
+ : null != u && 'object' === typeof u
1467
+ ? Object.keys(u).map((k) => o.universe + '.' + k) : undefined;
1468
+ if (undefined === all || !allStrings(all)) {
1469
+ return {
1470
+ errors: [shapeFinding(o.universe, 'The universe must be a map or a list of strings.')],
1471
+ };
1472
+ }
1473
+ for (const x of all) {
1474
+ elements.add(x);
1475
+ }
1476
+ }
1477
+ // An element written as an address is shown by the shortest suffix
1478
+ // that tells it from every other address in the panel, as a node
1479
+ // is; one written as a plain string is shown as written.
1480
+ const addressed = [...elements].filter((x) => x.startsWith('$.')).sort(keyorder_1.cmpCodePoint);
1481
+ const short = labelsOf(addressed);
1482
+ const shown = (x) => short.get(x) ?? x;
1483
+ let cols = columnsOf(names, members, [...elements], shown);
1484
+ if (undefined !== o.minDegree) {
1485
+ const least = o.minDegree;
1486
+ cols = cols.filter((c) => least <= c.sig.filter((b) => b).length);
1487
+ }
1488
+ cols = elide(cols, o.maxCols, loss);
1489
+ // A set name or an element is a generated string, and a string can
1490
+ // hold a line terminator; no line of the panel can.
1491
+ const broken = [...names, ...elements].find(hasLineBreak);
1492
+ if (undefined !== broken) {
1493
+ return { errors: [lineBreakFinding(o.sets)] };
1494
+ }
1495
+ const panel = {
1496
+ header: `# upset sets=${o.sets}(${names.length}) member=${o.member}` +
1497
+ ` elements=${elements.size}` +
1498
+ (undefined === o.universe ? '' : ` universe=${o.universe}`),
1499
+ names,
1500
+ sizes: names.map((n) => members.get(n).size),
1501
+ cols,
1502
+ bars: true,
1503
+ none: ' (in no set)',
1504
+ };
1505
+ return {
1506
+ text: 'svg' === o.as
1507
+ ? panelSvg(panel, `Set panel over ${o.sets}: ${names.length} sets, ` +
1508
+ `${elements.size} elements, ${cols.length} intersections`, o.style)
1509
+ : renderPanel(panel, o.style),
1510
+ };
1511
+ }
1512
+ // The file a contribution names, as the panel shows it: relative to
1513
+ // the entry document's directory, the entry itself by its own name.
1514
+ function docName(file, entry) {
1515
+ if ('' === file || file === entry) {
1516
+ return undefined === entry ? '-' : (0, node_path_1.basename)(entry);
1517
+ }
1518
+ return (0, node_path_1.isAbsolute)(file) && undefined !== entry
1519
+ ? (0, node_path_1.relative)((0, node_path_1.dirname)((0, node_path_1.resolve)(entry)), file) : file;
1520
+ }
1521
+ function drawLayers(prov, root, entry, o, max, loss) {
1522
+ // Every path something met at AND THE DOCUMENT HAS A VALUE AT,
1523
+ // mapped to the documents that met there. A meet can happen at a
1524
+ // position the finished document does not have -- a template's own
1525
+ // child, folded into each key it is spread over -- and the panel is
1526
+ // about the document, so only its paths are rows. A path is shown
1527
+ // as `a.b.c`; the root as `$`.
1528
+ const members = new Map();
1529
+ const paths = [];
1530
+ const atParts = undefined === o.at ? [] : (0, query_1.pathParts)(o.at);
1531
+ for (const [key, rec] of prov.paths) {
1532
+ // A record at a position the document does not have is the Go
1533
+ // recorder's template ghost (use-cases/BUGS.md 70); this port's
1534
+ // recorder does not write one, and the two ports must skip the
1535
+ // same rows.
1536
+ if (0 === rec.conjuncts.length || null == (0, vet_1.anchorAt)(root, '$.' + key)) {
1537
+ continue;
1538
+ }
1539
+ const parts = '' === key ? [] : key.split('.');
1540
+ if (atParts.some((p, i) => parts[i] !== p)) {
1541
+ continue;
1542
+ }
1543
+ const shown = 0 === parts.length ? '$' : parts.join('.');
1544
+ paths.push(shown);
1545
+ for (const c of rec.conjuncts) {
1546
+ const d = docName(c.site.file, entry);
1547
+ let set = members.get(d);
1548
+ if (undefined === set) {
1549
+ set = new Set();
1550
+ members.set(d, set);
1551
+ }
1552
+ set.add(shown);
1553
+ }
1554
+ }
1555
+ const names = [...members.keys()].sort(keyorder_1.cmpCodePoint);
1556
+ if (max < names.length) {
1557
+ return { errors: [rowsFinding(names.length, max, '--at')] };
1558
+ }
1559
+ let cols = columnsOf(names, members, paths, (p) => p);
1560
+ if (undefined !== o.minSize) {
1561
+ const least = o.minSize;
1562
+ cols = cols.filter((c) => least <= c.items.length);
1563
+ }
1564
+ cols = elide(cols, o.maxCols, loss);
1565
+ const panel = {
1566
+ header: `# layers file=${undefined === entry ? '-' : (0, node_path_1.basename)(entry)}` +
1567
+ ` documents=${names.length} paths=${paths.length}`,
1568
+ names,
1569
+ sizes: names.map((n) => members.get(n).size),
1570
+ cols,
1571
+ bars: false,
1572
+ none: '',
1573
+ };
1574
+ return {
1575
+ text: 'svg' === o.as
1576
+ ? panelSvg(panel, `Document layers: ${names.length} documents, ` +
1577
+ `${paths.length} paths, ${cols.length} intersections`, o.style)
1578
+ : renderPanel(panel, o.style),
1579
+ };
1580
+ }
1581
+ // ---------------------------------------------------------------------
1582
+ // The meet ladder (VIEWS-ORDER.0.md)
1583
+ // The descent from `top` through each contribution to the resolved
1584
+ // value, one rung per conjunct. Where the contributions are ranked
1585
+ // preferences the ladder IS the arbitration: fewer stars win, so the
1586
+ // rungs read weakest-first and the winner is the last before the
1587
+ // value. `why`'s record is in source order, which is not rank order,
1588
+ // so the rungs are SORTED -- an emitter that trusted the record would
1589
+ // draw an arbitration that did not happen.
1590
+ function drawLadder(src, options, as, max) {
1591
+ if (undefined === options.at) {
1592
+ return {
1593
+ errors: [finding('view_at_required', 'reference', '$', 'The ladder needs the path to draw; name it with --at.')],
1594
+ };
1595
+ }
1596
+ const rep = (0, query_1.why)(src, options.at, { path: options.path, trust: options.trust });
1597
+ if (undefined === rep.record) {
1598
+ return { errors: rep.findings };
1599
+ }
1600
+ const rungs = rep.record.conjuncts.slice().sort((a, b) => (b.rank ?? 0) - (a.rank ?? 0)
1601
+ || (0, keyorder_1.cmpCodePoint)(a.site.file, b.site.file)
1602
+ || a.site.row - b.site.row
1603
+ || a.site.col - b.site.col);
1604
+ if (max < rungs.length) {
1605
+ return { errors: [rowsFinding(rungs.length, max, 'a narrower --at')] };
1606
+ }
1607
+ const where = (c) => `${(0, node_path_1.basename)(c.site.file)}:${c.site.row}:${c.site.col}`;
1608
+ const out = [];
1609
+ if ('mermaid' === as) {
1610
+ const esc = (s) => escape(s, MERMAID_ESC);
1611
+ out.push('graph TD', ' top(("top"))');
1612
+ rungs.forEach((c, i) => {
1613
+ out.push(` c${i}["${esc(c.canon)}<br/>${c.role} | ${esc(where(c))}"]`);
1614
+ });
1615
+ out.push(` val{{"${esc(rep.record.value)}"}}`);
1616
+ let prev = 'top';
1617
+ rungs.forEach((_c, i) => {
1618
+ out.push(` ${prev} --> c${i}`);
1619
+ prev = `c${i}`;
1620
+ });
1621
+ out.push(` ${prev} --> val`);
1622
+ }
1623
+ else {
1624
+ const esc = (s) => escape(s, DOT_ESC);
1625
+ out.push('digraph G {', ' rankdir=TB;', ' node [shape=box];', ' top [shape=circle, label="top"];');
1626
+ rungs.forEach((c, i) => {
1627
+ out.push(` c${i} [label="${esc(c.canon)}\\n${c.role} | ${esc(where(c))}"];`);
1628
+ });
1629
+ out.push(` val [shape=hexagon, label="${esc(rep.record.value)}"];`);
1630
+ let prev = 'top';
1631
+ rungs.forEach((_c, i) => {
1632
+ out.push(` ${prev} -> c${i};`);
1633
+ prev = `c${i}`;
1634
+ });
1635
+ out.push(` ${prev} -> val;`, '}');
1636
+ }
1637
+ return { text: out.join('\n') };
1638
+ }
1639
+ const compareBySubsume = (general, specific, options) => {
1640
+ const r = (0, subsume_1.subsume)(general.src, specific.src, {
1641
+ at: options.at, profile: options.profile,
1642
+ generalPath: general.path, specificPath: specific.path,
1643
+ trust: options.trust,
1644
+ });
1645
+ return { verdict: r.verdict, code: r.findings[0]?.code ?? 'undecided' };
1646
+ };
1647
+ function drawPoset(docs, options, as, max, loss, compare) {
1648
+ const n = docs.length;
1649
+ const verdict = docs.map(() => docs.map(() => 'subsumes'));
1650
+ const code = docs.map(() => docs.map(() => ''));
1651
+ let broken = false;
1652
+ for (let a = 0; a < n; a++) {
1653
+ for (let b = 0; b < n; b++) {
1654
+ if (a === b) {
1655
+ continue;
1656
+ }
1657
+ const r = compare(docs[a], docs[b], options);
1658
+ verdict[a][b] = r.verdict;
1659
+ code[a][b] = r.code;
1660
+ broken = broken || 'error' === r.verdict;
1661
+ }
1662
+ }
1663
+ if (broken) {
1664
+ return { errors: docs.flatMap((d) => docFailure(d, options)) };
1665
+ }
1666
+ const ge = (a, b) => 'subsumes' === verdict[a][b];
1667
+ // Quotient by mutual subsumption; class labels joined by ` = `.
1668
+ const classes = [];
1669
+ for (let i = 0; i < n; i++) {
1670
+ const found = classes.find((c) => ge(i, c.members[0]) && ge(c.members[0], i));
1671
+ if (undefined === found) {
1672
+ classes.push({ members: [i], label: '' });
1673
+ }
1674
+ else {
1675
+ found.members.push(i);
1676
+ }
1677
+ }
1678
+ for (const c of classes) {
1679
+ c.members.sort((x, y) => (0, keyorder_1.cmpCodePoint)(docs[x].label, docs[y].label));
1680
+ c.label = c.members.map((m) => docs[m].label).join(' = ');
1681
+ }
1682
+ classes.sort((x, y) => (0, keyorder_1.cmpCodePoint)(x.label, y.label));
1683
+ if (max < classes.length) {
1684
+ return { errors: [rowsFinding(classes.length, max, 'fewer documents')] };
1685
+ }
1686
+ for (const c of classes) {
1687
+ if (hasLineBreak(c.label)) {
1688
+ return { errors: [lineBreakFinding('$')] };
1689
+ }
1690
+ }
1691
+ // closure[lo][hi]: hi subsumes lo, directly or by transitivity.
1692
+ const k = classes.length;
1693
+ const rep = (ci) => classes[ci].members[0];
1694
+ const closure = classes.map((_x, lo) => classes.map((_y, hi) => lo !== hi && ge(rep(hi), rep(lo))));
1695
+ for (let m = 0; m < k; m++) {
1696
+ for (let i = 0; i < k; i++) {
1697
+ for (let j = 0; j < k; j++) {
1698
+ if (closure[i][m] && closure[m][j]) {
1699
+ closure[i][j] = true;
1700
+ }
1701
+ }
1702
+ }
1703
+ }
1704
+ const covers = [];
1705
+ const intransitive = [];
1706
+ for (let lo = 0; lo < k; lo++) {
1707
+ for (let hi = 0; hi < k; hi++) {
1708
+ if (!closure[lo][hi]) {
1709
+ continue;
1710
+ }
1711
+ // A pair the closure implies but the checker measured as
1712
+ // `does_not_subsume` is reported rather than absorbed: the
1713
+ // measured relation is a conservative under-approximation, and
1714
+ // an under-approximation of a transitive relation need not be
1715
+ // transitive.
1716
+ if ('does_not_subsume' === verdict[rep(hi)][rep(lo)]) {
1717
+ intransitive.push(`${classes[lo].label} < ${classes[hi].label}`);
1718
+ }
1719
+ const viaMid = classes.some((_c, mid) => mid !== lo && mid !== hi && closure[lo][mid] && closure[mid][hi]);
1720
+ if (!viaMid) {
1721
+ covers.push([lo, hi]);
1722
+ }
1723
+ }
1724
+ }
1725
+ if (0 < intransitive.length) {
1726
+ loss.push({
1727
+ code: 'order_intransitive', count: intransitive.length,
1728
+ detail: intransitive,
1729
+ });
1730
+ }
1731
+ // An undecided pair with no proven order either way is a DASHED edge
1732
+ // in the queried direction, labelled with the reason; one proven one
1733
+ // way and undecided the other keeps its solid edge and is reported,
1734
+ // since the two may be equal and the checker cannot tell.
1735
+ const dashed = [];
1736
+ const maybeEqual = [];
1737
+ for (let g = 0; g < k; g++) {
1738
+ for (let s = 0; s < k; s++) {
1739
+ if (g === s || 'undecided' !== verdict[rep(g)][rep(s)]) {
1740
+ continue;
1741
+ }
1742
+ if (closure[s][g] || closure[g][s]) {
1743
+ maybeEqual.push(`${classes[s].label} ~ ${classes[g].label}`);
1744
+ }
1745
+ else {
1746
+ dashed.push([s, g, code[rep(g)][rep(s)]]);
1747
+ }
1748
+ }
1749
+ }
1750
+ if (0 < dashed.length) {
1751
+ loss.push({
1752
+ code: 'order_undecided', count: dashed.length,
1753
+ detail: dashed.map(([s, g, c]) => `${classes[s].label} ~ ${classes[g].label} (${c})`),
1754
+ });
1755
+ }
1756
+ if (0 < maybeEqual.length) {
1757
+ loss.push({
1758
+ code: 'order_maybe_equal', count: maybeEqual.length, detail: maybeEqual,
1759
+ });
1760
+ }
1761
+ const head = 'aontu subsumption poset' +
1762
+ (undefined === options.at ? '' : ` at=${options.at}`) +
1763
+ ` profile=${options.profile ?? 'defaults'}` +
1764
+ ` documents=${n} nodes=${k}`;
1765
+ const out = [];
1766
+ if ('mermaid' === as) {
1767
+ const esc = (s) => escape(s, MERMAID_ESC);
1768
+ out.push('%% ' + head, 'graph BT');
1769
+ classes.forEach((c, i) => {
1770
+ out.push(` n${i}["${esc(c.label)}"]`);
1771
+ });
1772
+ for (const [lo, hi] of covers) {
1773
+ out.push(` n${lo} --> n${hi}`);
1774
+ }
1775
+ for (const [s, g, c] of dashed) {
1776
+ out.push(` n${s} -.->|"${esc(c)}"| n${g}`);
1777
+ }
1778
+ }
1779
+ else {
1780
+ const esc = (s) => escape(s, DOT_ESC);
1781
+ out.push('// ' + head, 'digraph G {', ' rankdir=BT;', ' node [shape=box];');
1782
+ classes.forEach((c, i) => {
1783
+ out.push(` n${i} [label="${esc(c.label)}"];`);
1784
+ });
1785
+ for (const [lo, hi] of covers) {
1786
+ out.push(` n${lo} -> n${hi};`);
1787
+ }
1788
+ for (const [s, g, c] of dashed) {
1789
+ out.push(` n${s} -> n${g} [style=dashed, label="${esc(c)}"];`);
1790
+ }
1791
+ out.push('}');
1792
+ }
1793
+ return { text: out.join('\n') };
1794
+ }
1795
+ // Why a poset could not be drawn: the documents that do not stand up
1796
+ // on their own, each with its own finding, or the anchor a document
1797
+ // lacks.
1798
+ function docFailure(d, options) {
1799
+ const loaded = load(d.src, d.path, options.trust, undefined);
1800
+ if (undefined !== loaded.errors) {
1801
+ return loaded.errors;
1802
+ }
1803
+ if (undefined !== options.at && null == (0, vet_1.anchorAt)(loaded.root, options.at)) {
1804
+ return [finding('no_path', 'reference', options.at, `${d.label} has no value at ${options.at}.`)];
1805
+ }
1806
+ return [];
1807
+ }
1808
+ // One evaluation, parsed and unified separately so the provenance
1809
+ // recorder can stamp the parsed tree before the fixpoint runs (`why`'s
1810
+ // precedent).
1811
+ function load(src, path, trust, prov) {
1812
+ const aontu = new aontu_1.Aontu(null == trust ? undefined : { trust });
1813
+ const ctx = aontu.ctx({ collect: true, prov });
1814
+ const parseOpts = null == path ? undefined : { path };
1815
+ const parsed = aontu.parse(src, parseOpts, ctx);
1816
+ if (0 < ctx.err.length || null == parsed) {
1817
+ return { errors: [(0, vet_1.failureFinding)(ctx, path, parsed)] };
1818
+ }
1819
+ if (undefined !== prov) {
1820
+ prov.writtenFrom(parsed);
1821
+ }
1822
+ const root = aontu.unify(parsed, parseOpts, ctx);
1823
+ // A document that does not stand up has no figure: the errors it
1824
+ // already has are the answer.
1825
+ if (0 < ctx.err.length || true === root?.isNil) {
1826
+ return { errors: [(0, vet_1.failureFinding)(ctx, path, root)] };
1827
+ }
1828
+ return { root, ctx };
1829
+ }
1830
+ // A figure of one document (or, for the poset, of a set of them).
1831
+ function view(src, opts, hooks) {
1832
+ const options = opts ?? {};
1833
+ const compare = hooks?.compare ?? compareBySubsume;
1834
+ const kind = options.kind ?? 'tree';
1835
+ const loss = [];
1836
+ const done = (fig) => {
1837
+ if (undefined !== fig.errors) {
1838
+ return { verdict: 'error', kind, loss: [], errors: fig.errors };
1839
+ }
1840
+ loss.sort((a, b) => (0, keyorder_1.cmpCodePoint)(a.code, b.code));
1841
+ const lossy = loss.some((l) => !INFORMATIONAL.includes(l.code));
1842
+ return { verdict: lossy ? 'lossy' : 'rendered', kind, text: fig.text, loss };
1843
+ };
1844
+ const profiles = PROFILES[kind];
1845
+ if (undefined === profiles) {
1846
+ return done({
1847
+ errors: [finding('view_kind_unknown', 'reference', '$', `${kind} is not a figure kind.`, 'kinds: ' + Object.keys(PROFILES).join(', '))],
1848
+ });
1849
+ }
1850
+ const as = options.as ?? profiles[0];
1851
+ if (!profiles.includes(as)) {
1852
+ return done({
1853
+ errors: [finding('view_profile_unknown', 'reference', '$', `The ${kind} figure does not render as ${as}.`, `profiles: ${profiles.join(', ')}`)],
1854
+ });
1855
+ }
1856
+ // ONE MECHANISM PER PROFILE (VIEWS.0.md, "7. Styling"). `ansi` is
1857
+ // the text profile's and `css` the SVG's; asking for one on a
1858
+ // profile that has no way to carry it is a usage error rather than a
1859
+ // silent no-op, so a script that asks for colour and gets none is
1860
+ // told why. `none` is always available -- it is the absence of a
1861
+ // mechanism.
1862
+ const style = styleOf(options.style, as);
1863
+ const carrier = { ansi: 'text', css: 'svg' };
1864
+ if (undefined !== carrier[style] && carrier[style] !== as) {
1865
+ return done({
1866
+ errors: [finding('view_style_profile', 'reference', '$', `The ${as} profile cannot carry --style ${style}.`, `${style} is the ${carrier[style]} profile's mechanism`)],
1867
+ });
1868
+ }
1869
+ if (undefined === carrier[style] && 'none' !== style) {
1870
+ return done({
1871
+ errors: [finding('view_style_unknown', 'reference', '$', `${style} is not a style.`, 'styles: auto, none, ansi, css')],
1872
+ });
1873
+ }
1874
+ // Zero means the default, in both ports.
1875
+ const max = options.maxRows || DEFAULT_MAX_ROWS;
1876
+ if ('poset' === kind) {
1877
+ const docs = [{ src, path: options.path }, ...(options.docs ?? [])]
1878
+ .map((d, i) => ({
1879
+ src: d.src, path: d.path,
1880
+ label: d.name ?? (undefined === d.path
1881
+ ? `doc${i + 1}` : (0, node_path_1.basename)(d.path).replace(/\.aon$/, '')),
1882
+ }));
1883
+ return done(drawPoset(docs, options, as, max, loss, compare));
1884
+ }
1885
+ if ('ladder' === kind) {
1886
+ return done(drawLadder(src, options, as, max));
1887
+ }
1888
+ const prov = 'layers' === kind
1889
+ ? (hooks?.provenance ?? (() => new provenance_1.Provenance()))() : undefined;
1890
+ const loaded = load(src, options.path, options.trust, prov);
1891
+ if (undefined !== loaded.errors) {
1892
+ return done({ errors: loaded.errors });
1893
+ }
1894
+ return done(drawLoaded(loaded.root, loaded.ctx, undefined, prov, kind, as, options, max, loss));
1895
+ }
1896
+ // THE KINDS THAT DRAW FROM A LOADED MODEL, so a view document can load
1897
+ // once and draw N figures from the one evaluation. `gen` is the
1898
+ // generated value where the caller already holds it -- a view document
1899
+ // reads its own declarations out of one -- and undefined where the set
1900
+ // panel must generate its own. It is a BOX rather than the value, so
1901
+ // that a document generating `undefined` is still a value the panel
1902
+ // has rather than one it must recompute.
1903
+ function drawLoaded(root, ctx, gen, prov, kind, as, options, max, loss) {
1904
+ const style = styleOf(options.style, as);
1905
+ if ('doc' === kind) {
1906
+ return drawDoc(root, { ...options, as, style }, max, loss);
1907
+ }
1908
+ if ('layers' === kind) {
1909
+ return drawLayers(prov, root, options.path, { ...options, as, style }, max, loss);
1910
+ }
1911
+ if ('sets' === kind) {
1912
+ if (undefined === options.sets || undefined === options.member) {
1913
+ return {
1914
+ errors: [finding('view_sets_required', 'reference', '$', 'The set panel needs --sets and --member.')],
1915
+ };
1916
+ }
1917
+ let value = gen?.value;
1918
+ if (undefined === gen) {
1919
+ // GENERATION CAN FAIL WHERE UNIFICATION DID NOT: the panel reads
1920
+ // generated values, so a document that is not concrete is an
1921
+ // error here, exactly as `aontu file.aon` on it is.
1922
+ const before = ctx.err.length;
1923
+ value = root.gen(ctx);
1924
+ if (before < ctx.err.length) {
1925
+ const err = ctx.err[before];
1926
+ return {
1927
+ errors: [finding(err?.why ?? 'unify_failed', 'reference', '$', err?.msg ?? 'The document does not generate.')],
1928
+ };
1929
+ }
1930
+ }
1931
+ return drawSets(value, {
1932
+ sets: options.sets, member: options.member, universe: options.universe,
1933
+ minDegree: options.minDegree, maxCols: options.maxCols, as, style,
1934
+ }, max, loss);
1935
+ }
1936
+ const triples = triplesOf((0, graph_1.graphOf)(root), options.at, loss);
1937
+ const decls = ctx._reldecls;
1938
+ // An empty relation name is no relation, so both ports read it as
1939
+ // "every relation" rather than one that names nothing.
1940
+ const relation = options.relation || undefined;
1941
+ if ('matrix' === kind) {
1942
+ return drawMatrix(triples, decls, {
1943
+ relation, order: options.order ?? 'canon', closure: true === options.closure,
1944
+ as, style,
1945
+ }, max, loss);
1946
+ }
1947
+ if ('graph' === kind) {
1948
+ return drawGraph(triples, decls, root, {
1949
+ relations: options.relations ?? [], groupBy: options.groupBy,
1950
+ label: options.label, as,
1951
+ }, max, loss);
1952
+ }
1953
+ if ('layer' === kind) {
1954
+ return drawLayer(triples, root, {
1955
+ relation, groupBy: options.groupBy, layers: options.layers ?? [],
1956
+ edges: options.edges, as, style,
1957
+ }, max, loss);
1958
+ }
1959
+ return drawTree(collapse(triples, relation), relation, options.roots ?? [], max, as, style);
1960
+ }
1961
+ // The tree view of one document: `view` with the kind fixed.
1962
+ function viewTree(src, opts) {
1963
+ return view(src, { ...(opts ?? {}), kind: 'tree' });
1964
+ }
1965
+ // ---------------------------------------------------------------------
1966
+ // The view document (VIEWS.0.md, "6. The view document")
1967
+ //
1968
+ // A projection that runs in CI belongs in a file. A view document is an
1969
+ // ORDINARY document that includes the model and declares its figures as
1970
+ // data; `views` is the AUTHOR's key and nothing here knows the name
1971
+ // (ADR-010), which is why `--views` names the path.
1972
+ //
1973
+ // The declaration keys ARE the library's option names, which are the
1974
+ // CLI's flag names without the dashes: one vocabulary, three doors. A
1975
+ // declaration must name its `kind` and its `out` -- a figure in a file
1976
+ // that a review reads should say what it draws and where it goes,
1977
+ // rather than inheriting a default from whoever ran the verb.
1978
+ const DECL_TEXT = [
1979
+ 'kind', 'as', 'out', 'at', 'relation', 'order', 'groupBy', 'label',
1980
+ 'sets', 'member', 'universe', 'edges',
1981
+ ];
1982
+ // The options whose values are a closed set. A view document is the
1983
+ // artifact CI reads, so a typo here is a refusal rather than a silent
1984
+ // fall back to the default.
1985
+ const DECL_ENUM = {
1986
+ order: ['canon', 'partition'],
1987
+ edges: ['upward', 'all', 'none'],
1988
+ };
1989
+ const DECL_COUNT = ['maxRows', 'maxCols', 'minDegree', 'minSize', 'depth'];
1990
+ const DECL_FLAG = ['closure'];
1991
+ const DECL_LIST = ['roots', 'relations', 'layers'];
1992
+ const DECL_KEYS = [...DECL_TEXT, ...DECL_COUNT, ...DECL_FLAG, ...DECL_LIST]
1993
+ .sort(keyorder_1.cmpCodePoint);
1994
+ function documentFinding(path, message, note) {
1995
+ return finding('view_document_shape', 'reference', path, message, note);
1996
+ }
1997
+ function planOf(name, decl, at) {
1998
+ const where = `${at}.${name}`;
1999
+ const errors = [];
2000
+ if (null == decl || 'object' !== typeof decl || Array.isArray(decl)) {
2001
+ return { errors: [documentFinding(where, 'A view declaration is not a map.')] };
2002
+ }
2003
+ const opts = {};
2004
+ for (const key of Object.keys(decl).sort(keyorder_1.cmpCodePoint)) {
2005
+ const value = decl[key];
2006
+ if (DECL_TEXT.includes(key)) {
2007
+ if ('string' !== typeof value) {
2008
+ errors.push(documentFinding(`${where}.${key}`, `${key} must be a string.`));
2009
+ continue;
2010
+ }
2011
+ opts[key] = value;
2012
+ }
2013
+ else if (DECL_COUNT.includes(key)) {
2014
+ if ('number' !== typeof value || !Number.isInteger(value) || 0 > value) {
2015
+ errors.push(documentFinding(`${where}.${key}`, `${key} must be a whole number, zero or more.`));
2016
+ continue;
2017
+ }
2018
+ opts[key] = value;
2019
+ }
2020
+ else if (DECL_FLAG.includes(key)) {
2021
+ if ('boolean' !== typeof value) {
2022
+ errors.push(documentFinding(`${where}.${key}`, `${key} must be true or false.`));
2023
+ continue;
2024
+ }
2025
+ opts[key] = value;
2026
+ }
2027
+ else if (DECL_LIST.includes(key)) {
2028
+ if (!Array.isArray(value) || !allStrings(value)) {
2029
+ errors.push(documentFinding(`${where}.${key}`, `${key} must be a list of strings.`));
2030
+ continue;
2031
+ }
2032
+ opts[key] = value;
2033
+ }
2034
+ else {
2035
+ errors.push(documentFinding(`${where}.${key}`, `${key} is not a view option.`, 'options: ' + DECL_KEYS.join(', ')));
2036
+ }
2037
+ }
2038
+ for (const key of Object.keys(DECL_ENUM)) {
2039
+ const value = opts[key];
2040
+ if (undefined !== value && !DECL_ENUM[key].includes(value)) {
2041
+ errors.push(documentFinding(`${where}.${key}`, `${value} is not a ${key}.`, `${key}: ${DECL_ENUM[key].join(', ')}`));
2042
+ }
2043
+ }
2044
+ const kind = opts.kind;
2045
+ if (undefined === kind) {
2046
+ errors.push(documentFinding(where, 'A view declaration must name its kind.', 'kinds: ' + Object.keys(PROFILES).join(', ')));
2047
+ }
2048
+ else if (undefined === PROFILES[kind]) {
2049
+ errors.push(documentFinding(`${where}.kind`, `${kind} is not a figure kind.`, 'kinds: ' + Object.keys(PROFILES).join(', ')));
2050
+ }
2051
+ else if ('poset' === kind) {
2052
+ // The poset is an order over SEVERAL documents, and a view document
2053
+ // declares figures of the one it includes. `aontu view poset` draws
2054
+ // it, naming the documents on the command line.
2055
+ errors.push(documentFinding(`${where}.kind`, 'A view document draws figures of one document; ' +
2056
+ 'the poset compares several.'));
2057
+ }
2058
+ const profiles = undefined === kind ? undefined : PROFILES[kind];
2059
+ const as = opts.as ?? profiles?.[0];
2060
+ if (undefined !== profiles && undefined !== as && !profiles.includes(as)) {
2061
+ errors.push(documentFinding(`${where}.as`, `The ${kind} figure does not render as ${as}.`, `profiles: ${profiles.join(', ')}`));
2062
+ }
2063
+ const out = opts.out;
2064
+ if (undefined === out || '' === out) {
2065
+ errors.push(documentFinding(where, 'A view declaration must name the file it draws into, as out.'));
2066
+ }
2067
+ else if (hasLineBreak(out)) {
2068
+ errors.push(documentFinding(`${where}.out`, 'A file name cannot hold a line terminator.'));
2069
+ }
2070
+ if (0 < errors.length) {
2071
+ return { errors };
2072
+ }
2073
+ return {
2074
+ plan: {
2075
+ name, kind: kind, as: as, out: out,
2076
+ max: opts.maxRows || DEFAULT_MAX_ROWS, opts,
2077
+ },
2078
+ errors: [],
2079
+ };
2080
+ }
2081
+ // N FIGURES OF ONE DOCUMENT. The document is evaluated ONCE, with the
2082
+ // provenance recorder on, and every figure but the ladder draws from
2083
+ // that one root; the ladder re-runs `why` by construction.
2084
+ //
2085
+ // The caller writes the files, and only when the whole set rendered:
2086
+ // N figures of one model are only meaningful together, so a set whose
2087
+ // third figure refuses must not leave the first two on disk.
2088
+ function viewSet(src, opts, hooks) {
2089
+ const options = opts ?? {};
2090
+ const at = options.views;
2091
+ if (undefined === at || '' === at) {
2092
+ return {
2093
+ verdict: 'error', views: [],
2094
+ errors: [documentFinding('$', 'The view document needs the path of ' +
2095
+ 'the map that declares the figures; name it with --views.')],
2096
+ };
2097
+ }
2098
+ // ONE EVALUATION, and it is INSTRUMENTED: the layers panel reads the
2099
+ // provenance record, which is written during unification, so a set
2100
+ // that declares one would otherwise need a second run. Recording it
2101
+ // always costs a little and makes the one-evaluation claim true for
2102
+ // every kind but the ladder, which re-runs `why` by construction.
2103
+ const prov = (hooks?.provenance ?? (() => new provenance_1.Provenance()))();
2104
+ const loaded = load(src, options.path, options.trust, prov);
2105
+ if (undefined !== loaded.errors) {
2106
+ return { verdict: 'error', views: [], errors: loaded.errors };
2107
+ }
2108
+ const root = loaded.root;
2109
+ const ctx = loaded.ctx;
2110
+ // The declarations are part of the document, so reading them
2111
+ // generates it -- and a view document that does not generate has no
2112
+ // figures, exactly as `aontu file.aon` on it has no output.
2113
+ const before = ctx.err.length;
2114
+ const value = root.gen(ctx);
2115
+ if (before < ctx.err.length) {
2116
+ const err = ctx.err[before];
2117
+ return {
2118
+ verdict: 'error', views: [],
2119
+ errors: [finding(err?.why ?? 'unify_failed', 'reference', '$', err?.msg ?? 'The document does not generate.')],
2120
+ };
2121
+ }
2122
+ const declared = genAt(value, at);
2123
+ if (null == declared || 'object' !== typeof declared || Array.isArray(declared)) {
2124
+ return {
2125
+ verdict: 'error', views: [],
2126
+ errors: [documentFinding(at, 'The view declarations are not a map.')],
2127
+ };
2128
+ }
2129
+ const plans = [];
2130
+ const errors = [];
2131
+ for (const name of Object.keys(declared).sort(keyorder_1.cmpCodePoint)) {
2132
+ const planned = planOf(name, declared[name], at);
2133
+ errors.push(...planned.errors);
2134
+ if (undefined !== planned.plan) {
2135
+ plans.push(planned.plan);
2136
+ }
2137
+ }
2138
+ if (0 < errors.length) {
2139
+ return { verdict: 'error', views: [], errors };
2140
+ }
2141
+ const gen = { value };
2142
+ const views = plans.map((plan) => {
2143
+ const loss = [];
2144
+ const each = {
2145
+ ...plan.opts, path: options.path, trust: options.trust,
2146
+ };
2147
+ const fig = 'ladder' === plan.kind
2148
+ ? drawLadder(src, each, plan.as, plan.max)
2149
+ : drawLoaded(root, ctx, gen, prov, plan.kind, plan.as, each, plan.max, loss);
2150
+ if (undefined !== fig.errors) {
2151
+ return {
2152
+ name: plan.name, kind: plan.kind, out: plan.out,
2153
+ verdict: 'error', loss: [], errors: fig.errors,
2154
+ };
2155
+ }
2156
+ loss.sort((a, b) => (0, keyorder_1.cmpCodePoint)(a.code, b.code));
2157
+ const lossy = loss.some((l) => !INFORMATIONAL.includes(l.code));
2158
+ return {
2159
+ name: plan.name, kind: plan.kind, out: plan.out,
2160
+ verdict: (lossy ? 'lossy' : 'rendered'),
2161
+ text: fig.text, loss,
2162
+ };
2163
+ });
2164
+ const verdict = views.some((v) => 'error' === v.verdict)
2165
+ ? 'error' : views.some((v) => 'lossy' === v.verdict) ? 'lossy' : 'rendered';
2166
+ return { verdict, views };
2167
+ }
2168
+ //# sourceMappingURL=view.js.map