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