context-mapper 0.20.2__py3-none-any.whl

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.
@@ -0,0 +1 @@
1
+ """Build a context map site from a model file and a style file."""
@@ -0,0 +1,6 @@
1
+ """Run the build with `python -m context_mapper`."""
2
+
3
+ from context_mapper.build import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,137 @@
1
+ """Build the context map from a model file (what it describes) and a style file (how it looks).
2
+
3
+ Writes an interactive page (index.html), one static Mermaid page per view
4
+ (mermaid/*.html) and the same diagrams as Markdown (markdown/*.md), all under
5
+ the output directory.
6
+
7
+ Fails (exit 1) on unknown ids, duplicates, dependency cycles between bounded
8
+ contexts, and unknown or invalid Mermaid options, so a bad change breaks the
9
+ pipeline instead of the picture.
10
+ """
11
+ import argparse
12
+ import json
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ import yaml
17
+
18
+ from . import graph, mermaid
19
+
20
+ TEMPLATE_DIR = Path(__file__).parent / "template"
21
+ DIAGRAMS_KEYS = {"types", "clusters", "context-map", "mermaid"}
22
+
23
+
24
+ class StrictLoader(yaml.SafeLoader):
25
+ """A SafeLoader that refuses duplicate keys, which would otherwise silently overwrite each other."""
26
+
27
+
28
+ def _construct_mapping(loader, node, deep=False):
29
+ loader.flatten_mapping(node)
30
+ mapping = {}
31
+ for key_node, value_node in node.value:
32
+ key = loader.construct_object(key_node, deep=deep)
33
+ if key in mapping:
34
+ raise yaml.constructor.ConstructorError(
35
+ "while constructing a mapping", node.start_mark,
36
+ f"found duplicate key {key!r}", key_node.start_mark)
37
+ mapping[key] = loader.construct_object(value_node, deep=deep)
38
+ return mapping
39
+
40
+
41
+ StrictLoader.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, _construct_mapping)
42
+
43
+
44
+ def read_yaml(path):
45
+ try:
46
+ return yaml.load(path.read_text(), Loader=StrictLoader)
47
+ except yaml.YAMLError as err:
48
+ sys.exit(f"error: {path}: {err}")
49
+
50
+
51
+ def add_input_flags(parser):
52
+ """The flags shared by the build and the serve commands."""
53
+ parser.add_argument("--model", type=Path, default=Path("context-map.yml"),
54
+ help="the model file (default: %(default)s)")
55
+ parser.add_argument("--diagrams", type=Path, default=Path("context-map.style.yml"),
56
+ help="the style file (default: %(default)s)")
57
+ parser.add_argument("--out", type=Path, default=Path("public"),
58
+ help="the directory to build into (default: %(default)s)")
59
+
60
+
61
+ def parse_args(argv=None):
62
+ parser = argparse.ArgumentParser(
63
+ prog="context-mapper",
64
+ description="Build a context map site from a model file (what it describes) "
65
+ "and a style file (how it looks).",
66
+ epilog="Run 'context-mapper serve --watch' to serve the site and rebuild it "
67
+ "whenever the YAML files change.")
68
+ add_input_flags(parser)
69
+ return parser.parse_args(argv)
70
+
71
+
72
+ def load(model_path, diagrams_path):
73
+ model = read_yaml(model_path)
74
+ diagrams = read_yaml(diagrams_path) or {}
75
+ data, errors = graph.normalize(model, diagrams)
76
+
77
+ for key in diagrams:
78
+ if key not in DIAGRAMS_KEYS:
79
+ errors.append(f"context-map.style.yml: {key}: unknown section. Known: {', '.join(sorted(DIAGRAMS_KEYS))}")
80
+
81
+ mermaid_cfg, mermaid_errors = mermaid.settings(diagrams.get("mermaid"))
82
+ errors += mermaid_errors
83
+
84
+ if not errors:
85
+ errors += mermaid.check(data, mermaid_cfg)
86
+
87
+ if errors:
88
+ for err in errors:
89
+ print(f"error: {err}", file=sys.stderr)
90
+ sys.exit(1)
91
+
92
+ # Contexts may depend on each other across domains in both directions without
93
+ # forming a context cycle. At domain level that is still worth knowing about.
94
+ cycle = graph.find_cycle(graph.level_graph(data, "domain"))
95
+ if cycle:
96
+ _, _, _, names = graph.index(data)
97
+ print("warning: domains depend on each other: " + " -> ".join(names[node] for node in cycle), file=sys.stderr)
98
+
99
+ return data, diagrams.get("mermaid")
100
+
101
+
102
+ def render_index(payload):
103
+ """The interactive page: the skeleton with the stylesheet, the script and the model spliced in."""
104
+ html = (TEMPLATE_DIR / "index.html").read_text()
105
+ css = (TEMPLATE_DIR / "style.css").read_text().strip()
106
+ js = (TEMPLATE_DIR / "app.js").read_text().replace("/*__MODEL__*/null", payload).strip()
107
+ return html.replace("/*__STYLE__*/", css).replace("/*__SCRIPT__*/", js)
108
+
109
+
110
+ def build_site(args):
111
+ """Build the whole site into args.out. Exits on missing or invalid input."""
112
+ for flag, path in (("--model", args.model), ("--diagrams", args.diagrams)):
113
+ if not path.exists():
114
+ sys.exit(f"error: {path} not found. Pass {flag} to set the path.")
115
+ data, mermaid_section = load(args.model, args.diagrams)
116
+ mermaid_cfg, _ = mermaid.settings(mermaid_section)
117
+ payload = json.dumps({**data, "mermaid": mermaid.client_settings(mermaid_cfg)}, ensure_ascii=False).replace("</", "<\\/")
118
+ html = render_index(payload)
119
+ index = args.out / "index.html"
120
+ args.out.mkdir(parents=True, exist_ok=True)
121
+ index.write_text(html)
122
+ print(f"built {index}: {len(data['domains'])} domains, "
123
+ f"{len(data['contexts'])} bounded contexts, {len(data['edges'])} dependencies")
124
+ count = mermaid.build(data, mermaid_section, args.out)
125
+ print(f"built {count} Mermaid views in {args.out}/mermaid/ and {args.out}/markdown/")
126
+
127
+
128
+ def main(argv=None):
129
+ argv = sys.argv[1:] if argv is None else list(argv)
130
+ if argv and argv[0] == "serve":
131
+ from .serve import serve
132
+ return serve(argv[1:])
133
+ build_site(parse_args(argv))
134
+
135
+
136
+ if __name__ == "__main__":
137
+ main()
@@ -0,0 +1,428 @@
1
+ """Normalized domain model and graph walks shared by the build and the Mermaid renderer.
2
+
3
+ Two levels:
4
+ - context: nodes are bounded contexts, plus multi-context domains (for dependencies
5
+ that point at a domain as a whole). Edges are as written in context-map.yml.
6
+ - domain: nodes are domains. Edges are lifted from contexts to their domains,
7
+ merged, and edges inside a domain are dropped.
8
+
9
+ Three kinds of thing, in three sections: `types` is the role vocabulary of the
10
+ model (a domain or bounded context has one, and it colors the box), `clusters`
11
+ names a set of domains or contexts treated together (members point at one with
12
+ `cluster:`), and `context-map` maps each id to what it is. A cluster holds
13
+ members; a domain holds bounded contexts; neither can be depended on or hold
14
+ the other's children. How anything first renders comes from `defaultDisplay` in
15
+ the style file: a domain or a cluster can be expanded, collapsed, contents or
16
+ hidden; a bounded context — a domain no context points at is one too — is one
17
+ box with nothing inside, so it can only be expanded or hidden. No type name is
18
+ special.
19
+ """
20
+
21
+
22
+ # Mermaid classDef attributes a box style may set, in `types`, `clusters` and
23
+ # `context-map` alike. The build checks them, so a typo fails the build instead
24
+ # of drawing nothing.
25
+ BOX_STYLE_KEYS = {"color", "fill", "fill-opacity", "font-family", "font-size",
26
+ "font-weight", "opacity", "stroke", "stroke-dasharray",
27
+ "stroke-opacity", "stroke-width"}
28
+
29
+ # How a container first renders. expanded: the box and the boxes inside it.
30
+ # collapsed: the box alone, the inside hidden. contents: the inside alone, the
31
+ # box hidden. hidden: neither.
32
+ DISPLAY_STATES = ("expanded", "collapsed", "contents", "hidden")
33
+
34
+ # How a bounded context first renders — a domain no context points at is one
35
+ # too. It is a single box with nothing inside, so there is nothing to collapse
36
+ # and no contents to show: expanded draws the box, hidden doesn't.
37
+ BOX_DISPLAY_STATES = ("expanded", "hidden")
38
+
39
+ # What a style fills in when the entry doesn't say: readable text on a light box.
40
+ TEXT_DEFAULTS = {"color": "#1a1a1a"}
41
+
42
+
43
+ def classdef(attrs, defaults=TEXT_DEFAULTS):
44
+ """A Mermaid classDef string: the attributes as written, then the defaults not set."""
45
+ items = list((attrs or {}).items())
46
+ have = {key for key, _ in items}
47
+ items += [(key, value) for key, value in defaults.items() if key not in have]
48
+ return ",".join(f"{key}:{value}" for key, value in items)
49
+
50
+
51
+ def box_style(section, item_id, style, defaults, required, errors, allowed=None,
52
+ display_states=DISPLAY_STATES):
53
+ """Check one box style map and return its classDef string, or None when there is nothing to draw."""
54
+ if not style:
55
+ return None
56
+ allowed = allowed or BOX_STYLE_KEYS
57
+ if "defaultDisplay" in style and "defaultDisplay" in allowed and style["defaultDisplay"] not in display_states:
58
+ hint = "" if display_states is DISPLAY_STATES else " — a bounded context is one box, with nothing inside it"
59
+ errors.append(f"context-map.style.yml: {section}.{item_id}.defaultDisplay must be one of "
60
+ f"{', '.join(display_states)}{hint}")
61
+ for key in style:
62
+ if key not in allowed:
63
+ errors.append(f"context-map.style.yml: {section}.{item_id}.{key}: unknown option. "
64
+ f"Known: {', '.join(sorted(allowed))}")
65
+ if required and not set(required) <= style.keys():
66
+ errors.append(f"context-map.style.yml: {section}.{item_id} needs `{required[0]}` and `{required[1]}`")
67
+ attrs = {key: value for key, value in style.items() if key in BOX_STYLE_KEYS}
68
+ return classdef(attrs, defaults) if attrs else None
69
+
70
+
71
+ def normalize(model, styles=None):
72
+ """Turn context-map.yml and context-map.style.yml into {types, clusters, domains, contexts, edges}
73
+ plus a list of errors.
74
+
75
+ `styles` is the parsed context-map.style.yml. Its sections mirror the model's —
76
+ `types`, `clusters`, `context-map` — keyed by the same ids.
77
+ """
78
+ styles = styles or {}
79
+ type_styles = styles.get("types") or {}
80
+ cluster_styles = styles.get("clusters") or {}
81
+ entry_styles = styles.get("context-map") or {}
82
+ errors = []
83
+ domains, contexts, pending = [], [], []
84
+ model = model or {}
85
+
86
+ for section in ("types", "context-map"):
87
+ if not model.get(section):
88
+ errors.append(f"context-map.yml: `{section}` is missing or empty")
89
+ if errors:
90
+ return {"types": {}, "clusters": [], "domains": [], "contexts": [], "edges": []}, errors
91
+
92
+ types = {}
93
+ for type_id, type_entry in model["types"].items():
94
+ if not isinstance(type_entry, dict):
95
+ errors.append(f"context-map.yml: types.{type_id}: needs a map with `name`")
96
+ continue
97
+ for key in type_entry:
98
+ if key != "name":
99
+ errors.append(f"context-map.yml: types.{type_id}.{key}: unknown option. Known: name")
100
+ style = type_styles.get(type_id) or {}
101
+ mermaid_style = box_style("types", type_id, style, TEXT_DEFAULTS, ("fill", "stroke"), errors)
102
+ if mermaid_style is None:
103
+ errors.append(f"context-map.style.yml: types.{type_id} needs `fill` and `stroke`")
104
+ types[type_id] = {**type_entry, **style, "mermaid_style": mermaid_style}
105
+ for type_id in type_styles:
106
+ if type_id not in model["types"]:
107
+ errors.append(f"context-map.style.yml: types.{type_id}: unknown type, it is not in context-map.yml")
108
+
109
+ # A cluster names a set of domains or contexts treated together. It holds
110
+ # members, never bounded contexts, and nothing can depend on it.
111
+ raw_entries = model.get("context-map") or {}
112
+ if isinstance(raw_entries, list):
113
+ errors.append("context-map.yml: `context-map` must be a map keyed by id")
114
+ raw_entries = {}
115
+
116
+ raw_clusters = model.get("clusters") or {}
117
+ if isinstance(raw_clusters, list):
118
+ errors.append("context-map.yml: `clusters` must be a map keyed by cluster id")
119
+ raw_clusters = {}
120
+ cluster_ids = set(raw_clusters)
121
+ for cluster_id, cluster in raw_clusters.items():
122
+ if not isinstance(cluster, dict):
123
+ errors.append(f"context-map.yml: clusters.{cluster_id}: needs a map with `name`")
124
+ continue
125
+ for key in cluster:
126
+ if key != "name":
127
+ errors.append(f"context-map.yml: clusters.{cluster_id}.{key}: unknown option. Known: name")
128
+ if not cluster.get("name"):
129
+ errors.append(f"context-map.yml: clusters.{cluster_id}: needs a name")
130
+ if cluster_id in raw_entries:
131
+ errors.append(f"context-map.yml: clusters.{cluster_id}: '{cluster_id}' is also an entry in context-map")
132
+
133
+ for entry_id in entry_styles:
134
+ entry = raw_entries.get(entry_id)
135
+ if not isinstance(entry, dict):
136
+ errors.append(f"context-map.style.yml: context-map.{entry_id}: unknown entry, it is not in context-map.yml")
137
+ for cluster_id in cluster_styles:
138
+ if cluster_id not in cluster_ids:
139
+ errors.append(f"context-map.style.yml: clusters.{cluster_id}: unknown cluster, it is not in context-map.yml")
140
+
141
+ def check_keys(entry_id, entry, allowed):
142
+ for key in entry:
143
+ if key not in allowed:
144
+ errors.append(f"context-map.{entry_id}.{key}: unknown option. Known: {', '.join(sorted(allowed))}")
145
+ if not entry.get("name"):
146
+ errors.append(f"context-map.{entry_id}: needs a name")
147
+
148
+ def check_cluster(entry_id, cluster):
149
+ if cluster is None:
150
+ return
151
+ if not isinstance(cluster, str):
152
+ errors.append(f"context-map.{entry_id}: `cluster` must be an id")
153
+ elif cluster not in cluster_ids:
154
+ errors.append(f"context-map.{entry_id}: unknown cluster '{cluster}', it is not in `clusters`")
155
+
156
+ # An entry with a `domain:` key is a bounded context of that domain; any
157
+ # other entry is a domain, and one no context points at is a single bounded
158
+ # context. Every id, domain or context, is a key of this one map, so
159
+ # nothing can be described twice.
160
+ raw_domains, raw_contexts = [], []
161
+ member_of = {}
162
+ for entry_id, entry in raw_entries.items():
163
+ if not isinstance(entry, dict):
164
+ errors.append(f"context-map.{entry_id}: needs a map with `name` and `type`")
165
+ continue
166
+ if "domain" in entry:
167
+ check_keys(entry_id, entry, ("name", "domain", "type", "cluster", "downstreams", "description"))
168
+ if entry.get("cluster") is not None:
169
+ errors.append(f"context-map.{entry_id}: a bounded context is inside its domain "
170
+ "already, it can't also be in a cluster")
171
+ parent = raw_entries.get(entry.get("domain"))
172
+ if not isinstance(parent, dict) or "domain" in parent:
173
+ errors.append(f"context-map.{entry_id}: unknown domain '{entry.get('domain')}'")
174
+ raw_contexts.append((entry_id, entry))
175
+ else:
176
+ check_keys(entry_id, entry, ("name", "type", "cluster", "downstreams", "description"))
177
+ check_cluster(entry_id, entry.get("cluster"))
178
+ if entry.get("cluster") is not None:
179
+ member_of[entry_id] = entry["cluster"]
180
+ if entry.get("type") is None:
181
+ errors.append(f"context-map.{entry_id}: needs a type")
182
+ elif entry.get("type") not in types:
183
+ errors.append(f"context-map.{entry_id}: unknown type '{entry.get('type')}'")
184
+ raw_domains.append((entry_id, entry))
185
+
186
+ for domain_id, domain in raw_domains:
187
+ domain_type, cluster = domain.get("type"), domain.get("cluster")
188
+ domain_style = entry_styles.get(domain_id) or {}
189
+ if "downstreams" in domain:
190
+ pending.append((domain_id, f"context-map.{domain_id}", domain["downstreams"]))
191
+ context_ids = []
192
+ for context_id, context in raw_contexts:
193
+ if context.get("domain") != domain_id:
194
+ continue
195
+ context_name, context_type = context.get("name"), context.get("type", domain_type)
196
+ if context_type not in types:
197
+ errors.append(f"context '{context_id}': unknown type '{context_type}'")
198
+ context_style = entry_styles.get(context_id) or {}
199
+ context_mermaid_style = box_style("context-map", context_id, context_style, TEXT_DEFAULTS, (), errors,
200
+ allowed=BOX_STYLE_KEYS | {"defaultDisplay"},
201
+ display_states=BOX_DISPLAY_STATES)
202
+ contexts.append({"id": context_id, "name": context_name, "type": context_type, "domain": domain_id,
203
+ "description": context.get("description"),
204
+ "mermaid_style": context_mermaid_style,
205
+ "defaultDisplay": context_style.get("defaultDisplay")})
206
+ context_ids.append(context_id)
207
+ if "downstreams" in context:
208
+ pending.append((context_id, f"context-map.{context_id}", context["downstreams"]))
209
+ # A domain with no bounded contexts is one itself: one box, with nothing
210
+ # inside, so its defaultDisplay is a bounded context's.
211
+ mermaid_style = box_style("context-map", domain_id, domain_style, TEXT_DEFAULTS, (), errors,
212
+ allowed=BOX_STYLE_KEYS | {"defaultDisplay"},
213
+ display_states=DISPLAY_STATES if context_ids else BOX_DISPLAY_STATES)
214
+ domains.append({"id": domain_id, "name": domain.get("name"), "type": domain_type, "cluster": cluster,
215
+ "contexts": context_ids, "single": not context_ids,
216
+ "mermaid_style": mermaid_style, "defaultDisplay": domain_style.get("defaultDisplay"),
217
+ "description": domain.get("description")})
218
+ if not context_ids:
219
+ contexts.append({"id": domain_id, "name": domain.get("name"), "type": domain_type, "domain": domain_id,
220
+ "description": domain.get("description"),
221
+ "defaultDisplay": domain_style.get("defaultDisplay")})
222
+
223
+ clusters = []
224
+ for cluster_id, cluster in raw_clusters.items():
225
+ style = cluster_styles.get(cluster_id) or {}
226
+ mermaid_style = box_style("clusters", cluster_id, style, TEXT_DEFAULTS, (), errors,
227
+ allowed=BOX_STYLE_KEYS | {"defaultDisplay"})
228
+ members = [member for member, member_cluster in member_of.items() if member_cluster == cluster_id]
229
+ if isinstance(cluster, dict) and not members and not errors:
230
+ errors.append(f"context-map.yml: clusters.{cluster_id}: no entry points at it with `cluster:`")
231
+ clusters.append({"id": cluster_id, "name": cluster.get("name") if isinstance(cluster, dict) else None,
232
+ "members": members, "mermaid_style": mermaid_style,
233
+ "defaultDisplay": style.get("defaultDisplay")})
234
+
235
+ seen = set(raw_entries)
236
+
237
+ edges = []
238
+ for owner, where, downstreams_map in pending:
239
+ # An edge points from the downstream (the one that depends) to the upstream.
240
+ # A downstream maps to why it depends on the upstream (the tooltip), or to
241
+ # {comment, style} when the edge also carries a style, or to nothing at all.
242
+ if not isinstance(downstreams_map, dict):
243
+ errors.append(f"{where}: `downstreams` must be a map from downstream to comment")
244
+ continue
245
+ if not downstreams_map:
246
+ errors.append(f"{where}: `downstreams` is empty")
247
+ continue
248
+ for downstream, spec in downstreams_map.items():
249
+ comment, edge_style = spec, "solid"
250
+ if isinstance(spec, dict):
251
+ for key in spec:
252
+ if key not in ("comment", "style"):
253
+ errors.append(f"{where}.downstreams.{downstream}.{key}: "
254
+ "unknown option. Known: comment, style")
255
+ comment, edge_style = spec.get("comment"), spec.get("style") or "solid"
256
+ elif spec is not None and not isinstance(spec, str):
257
+ errors.append(f"{where}.downstreams.{downstream}: must be a comment "
258
+ "string, or a map with `comment` and `style`")
259
+ for endpoint in (owner, downstream):
260
+ if endpoint not in seen:
261
+ errors.append(f"unknown domain or context '{endpoint}' in {where}.downstreams")
262
+ edges.append({"from": downstream, "to": owner, "style": edge_style, "comment": comment})
263
+
264
+ data = {"types": types, "clusters": clusters, "domains": domains, "contexts": contexts, "edges": edges}
265
+ if not errors:
266
+ cycle = find_cycle(level_graph(data, "context"))
267
+ if cycle:
268
+ errors.append("dependency cycle: " + " -> ".join(cycle))
269
+ return data, errors
270
+
271
+
272
+ def index(data):
273
+ """Lookups used everywhere: id -> item, and id -> owning domain id."""
274
+ domains = {domain["id"]: domain for domain in data["domains"]}
275
+ contexts = {context["id"]: context for context in data["contexts"]}
276
+ owner = {context["id"]: context["domain"] for context in data["contexts"]}
277
+ owner.update({domain["id"]: domain["id"] for domain in data["domains"]})
278
+ names = {**{domain["id"]: domain["name"] for domain in data["domains"]}, **{context["id"]: context["name"] for context in data["contexts"]}}
279
+ return domains, contexts, owner, names
280
+
281
+
282
+ def level_graph(data, level):
283
+ """Return {nodes: set, edges: [...], child_of: {node: container id}} for a level.
284
+
285
+ `child_of` says which container a node renders inside: a bounded context
286
+ inside its domain, a member inside its cluster."""
287
+ domains, contexts, owner, _ = index(data)
288
+ child_of = {domain["id"]: domain["cluster"] for domain in data["domains"] if domain["cluster"]}
289
+ if level == "context":
290
+ nodes = set(contexts) | {domain_id for domain_id, domain in domains.items() if not domain["single"]}
291
+ child_of.update({context_id: context["domain"] for context_id, context in contexts.items()
292
+ if not domains[context["domain"]]["single"]})
293
+ edges = [{"from": edge["from"], "to": edge["to"], "styles": {edge["style"]}, "via": [edge]} for edge in data["edges"]]
294
+ return {"nodes": nodes, "edges": edges, "child_of": child_of}
295
+
296
+ merged = {}
297
+ for edge in data["edges"]:
298
+ downstream_owner, upstream_owner = owner[edge["from"]], owner[edge["to"]]
299
+ if downstream_owner == upstream_owner:
300
+ continue
301
+ entry = merged.setdefault((downstream_owner, upstream_owner),
302
+ {"from": downstream_owner, "to": upstream_owner, "styles": set(), "via": []})
303
+ entry["styles"].add(edge["style"])
304
+ entry["via"].append(edge)
305
+ return {
306
+ "nodes": set(domains),
307
+ "edges": list(merged.values()),
308
+ "child_of": child_of,
309
+ }
310
+
311
+
312
+ def descendants(level_graph, ids):
313
+ """Each id and everything rendered inside it, at this level."""
314
+ kids = {}
315
+ for child, parent in level_graph["child_of"].items():
316
+ kids.setdefault(parent, []).append(child)
317
+ result, stack = set(), list(ids)
318
+ while stack:
319
+ node = stack.pop()
320
+ if node in result:
321
+ continue
322
+ result.add(node)
323
+ stack += kids.get(node, [])
324
+ return result
325
+
326
+
327
+ def find_cycle(level_graph):
328
+ adjacency = {node: [] for node in level_graph["nodes"]}
329
+ for edge in level_graph["edges"]:
330
+ adjacency[edge["from"]].append(edge["to"])
331
+ state, stack = {}, []
332
+
333
+ def visit(node):
334
+ state[node] = "open"
335
+ stack.append(node)
336
+ for next_node in adjacency[node]:
337
+ if state.get(next_node) == "open":
338
+ return stack[stack.index(next_node):] + [next_node]
339
+ if next_node not in state:
340
+ found = visit(next_node)
341
+ if found:
342
+ return found
343
+ stack.pop()
344
+ state[node] = "done"
345
+ return None
346
+
347
+ for node in sorted(level_graph["nodes"]):
348
+ if node not in state:
349
+ found = visit(node)
350
+ if found:
351
+ return found
352
+ return None
353
+
354
+
355
+ def focus_set(data, level, focus):
356
+ """The node ids a focus starts from at a level. A domain focus opens it: its
357
+ bounded contexts are starts too. A cluster focus opens it: its members —
358
+ and their bounded contexts there — are starts too."""
359
+ if not focus:
360
+ return set()
361
+ domains, _, owner, _ = index(data)
362
+ clusters = {cluster["id"]: cluster for cluster in data["clusters"]}
363
+ if focus in clusters:
364
+ starts = {focus, *clusters[focus]["members"]}
365
+ if level == "context":
366
+ for member in clusters[focus]["members"]:
367
+ starts.update(domains[member]["contexts"])
368
+ return starts
369
+ if level == "domain":
370
+ return {owner[focus]}
371
+ if focus in domains and not domains[focus]["single"]:
372
+ return {focus, *domains[focus]["contexts"]}
373
+ return {focus}
374
+
375
+
376
+ def walk(level_graph, starts, depth, direction, hidden):
377
+ """Nodes reachable from `starts` within `depth` hops. Without starts, every node.
378
+ `hidden` holds what isn't shown: a hidden container and everything inside it.
379
+ A start is always shown; one that isn't a node, like a cluster, only marks
380
+ itself. Reaching a container reaches what it holds, at the same hop: an edge
381
+ to a domain is an edge to the whole of it, so the walk goes on from its
382
+ bounded contexts too."""
383
+
384
+ def is_shown(node):
385
+ return node in starts or node not in hidden
386
+
387
+ if not starts:
388
+ return {node for node in level_graph["nodes"] if is_shown(node)}
389
+ upstreams_of = {node: [] for node in level_graph["nodes"]}
390
+ downstreams_of = {node: [] for node in level_graph["nodes"]}
391
+ for edge in level_graph["edges"]:
392
+ upstreams_of[edge["from"]].append(edge["to"])
393
+ downstreams_of[edge["to"]].append(edge["from"])
394
+ seen = set(starts)
395
+
396
+ def expand(adjacency):
397
+ frontier = list(starts)
398
+ for _ in range(depth):
399
+ next_frontier = []
400
+ for node in frontier:
401
+ for neighbor in adjacency.get(node, []):
402
+ for reached in descendants(level_graph, [neighbor]):
403
+ if reached not in seen and is_shown(reached):
404
+ seen.add(reached)
405
+ next_frontier.append(reached)
406
+ frontier = next_frontier
407
+
408
+ if direction != "down":
409
+ expand(upstreams_of)
410
+ if direction != "up":
411
+ expand(downstreams_of)
412
+ return seen
413
+
414
+
415
+ def relations(data, item_id):
416
+ """Direct dependencies of a context, or of a domain (lifted to domain level)."""
417
+ domains, _, _, names = index(data)
418
+ if item_id in domains and not domains[item_id]["single"]:
419
+ graph_at_level = level_graph(data, "domain")
420
+ else:
421
+ graph_at_level = level_graph(data, "context")
422
+ upstreams = [edge["to"] for edge in graph_at_level["edges"] if edge["from"] == item_id]
423
+ downstreams = [edge["from"] for edge in graph_at_level["edges"] if edge["to"] == item_id]
424
+
425
+ def name_of(entry_id):
426
+ return names[entry_id]
427
+
428
+ return sorted(upstreams, key=name_of), sorted(downstreams, key=name_of)