@krizaka/architecture 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,6 +24,35 @@ const units = unitsOf(files); // every unit with its version and the org depende
24
24
  Also exported: `isOrgPackage` (per ecosystem), `baseVersion` (`^0.19.0` → `0.19.0`) and `globMatches` (a workspace glob against
25
25
  a directory).
26
26
 
27
+ ## Laying views out (`layoutViews`, build time)
28
+
29
+ One layout step for every consumer (blog, docs sites, cockpit; the drawing is `@krizaka/ui`'s, which imports only the types
30
+ `ArchView`, `ArchNode`, `ArchEdge`, `Box` and `Point` from here). `layoutViews(model, options)` checks a LikeC4 model with the
31
+ org's rules, lays its views out with LikeC4's own parser and Graphviz, and returns the geometry — no network, no setting, the
32
+ same sources give the same JSON.
33
+
34
+ ```js
35
+ import { buildC4, layoutViews, ArchitectureModelError } from "@krizaka/architecture";
36
+ const out = await layoutViews([{ path: "agents.c4", text }], { base: orgFiles, system: "platform.tooling" });
37
+ // { schema: "krizaka.layout/1", tool, sources: { model, base } (sha256 of each file),
38
+ // check: { status: "ok", system, errors: [], elements }, views: ArchView[] }
39
+ const containers = await layoutViews(buildC4("/path/to/checkout")); // the containers view of a repo, no hand-written model
40
+ ```
41
+
42
+ `model` is a LikeC4 text, `[{ path, text }]` or the C4 `buildC4` returns. Options: `base` (the org's `specification.c4` and
43
+ `org.c4`: a model then writes no specification), `system` (a model only extends this system: every element it adds lives
44
+ inside it), `views` (ids to return, in this order; the implicit `index` landscape only when named). A model the check refuses
45
+ throws an `ArchitectureModelError` whose `rule` (`model`, `no-specification`, `home`, `views`) and `problems` (`path`, `line`,
46
+ `message`) say why. A dynamic view's edges carry their `step`; an edge Graphviz drew against its rank is `back` (its points run
47
+ from the target to the source). `@likec4/language-services` is pinned and does the parsing (ADR-026).
48
+
49
+ ```bash
50
+ npx krizaka-architecture layout model.c4 --out views.json --base specification.c4 --base org.c4 --system platform.tooling
51
+ npx krizaka-architecture layout ../my-repo --out views.json # a directory: its containers view, through buildC4
52
+ ```
53
+
54
+ Exit 0 when laid out, 1 with the rule when the model is refused, 2 on a bad call.
55
+
27
56
  ## The units and their versions (`unitsOf`)
28
57
 
29
58
  A unit is what a manifest declares, each with `path`, `manifest`, `ecosystem`, `language`, `name`, `version`, `published` (an org
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krizaka/architecture",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "The C4 view of a repository, generated from its code and manifests: containers from the workspaces (with their version and the org dependencies that build them, from the lockfile), Maven modules, crates and Python projects, components from the folders, the imports between them, the external services from the env declarations. Runs on a local checkout or a map of files, writes JSON and a text version.",
5
5
  "keywords": [
6
6
  "krizaka",
@@ -38,14 +38,15 @@
38
38
  ],
39
39
  "sideEffects": false,
40
40
  "dependencies": {
41
+ "@likec4/language-services": "1.60.0",
41
42
  "fast-xml-parser": "5.12.0",
42
43
  "smol-toml": "1.9.1",
43
- "yaml": "2.8.1"
44
+ "yaml": "2.8.3"
44
45
  },
45
46
  "devDependencies": {
46
47
  "@types/node": "^22.10.0",
47
48
  "eslint": "^9.39.0",
48
- "@krizaka/config": "^0.22.0"
49
+ "@krizaka/config": "^0.26.0"
49
50
  },
50
51
  "engines": {
51
52
  "node": ">=22"
package/src/cli.mjs CHANGED
@@ -1,12 +1,20 @@
1
1
  #!/usr/bin/env node
2
2
  // krizaka-architecture <repo-path> [--out c4.json] [--level context|containers|components] [--text [file]]
3
+ // krizaka-architecture layout <model.c4 | repo-path> [--out views.json] [--base f.c4]... [--system id] [--view id]...
3
4
  // Without --out the JSON goes to stdout. With --level the file holds that level only: { level, nodes, edges }.
4
5
  import { existsSync, writeFileSync } from "node:fs";
5
6
  import { resolve } from "node:path";
6
7
 
7
8
  import { buildC4, toText } from "./index.mjs";
9
+ import { runLayout } from "./layout-cli.mjs";
8
10
 
9
11
  const args = process.argv.slice(2);
12
+ if (args[0] === "layout") {
13
+ // exitCode, not exit(): a large JSON on a pipe must be flushed first
14
+ process.exitCode = await runLayout(args.slice(1));
15
+ await new Promise((done) => process.stdout.write("", done));
16
+ process.exit(process.exitCode);
17
+ }
10
18
  const flag = (name) => {
11
19
  const i = args.indexOf(`--${name}`);
12
20
  if (i < 0) return undefined;
package/src/index.d.ts CHANGED
@@ -90,3 +90,103 @@ export const isOrgPackage: Record<Ecosystem, (name: string) => boolean>;
90
90
  export function baseVersion(range: string | null | undefined): string | null;
91
91
  /** Does a directory match a workspace glob (`apps/*`, `packages/**`, `deploy/backup`)? */
92
92
  export function globMatches(glob: string, dir: string): boolean;
93
+
94
+ export type Point = readonly [number, number];
95
+ export interface Box {
96
+ x: number;
97
+ y: number;
98
+ width: number;
99
+ height: number;
100
+ }
101
+
102
+ /** A node of a laid-out view (pixels, rounded). `compound` nodes hold others (their `parent` points at them). */
103
+ export interface ArchNode extends Box {
104
+ id: string;
105
+ parent: string | null;
106
+ kind: string;
107
+ shape: string;
108
+ title: string;
109
+ technology: string | null;
110
+ description: string | null;
111
+ compound: boolean;
112
+ }
113
+
114
+ export interface ArchEdge {
115
+ id: string;
116
+ source: string;
117
+ target: string;
118
+ label: string | null;
119
+ /** Bézier points, start to end (or target to source when `back`). */
120
+ points: readonly Point[];
121
+ labelBBox: Box | null;
122
+ /** The step number of a dynamic view's edge, in the model's order; null in a static view. */
123
+ step: number | null;
124
+ /** Graphviz drew the edge against its rank: the points run from the target to the source. */
125
+ back: boolean;
126
+ }
127
+
128
+ export interface ArchView {
129
+ id: string;
130
+ title: string;
131
+ dynamic: boolean;
132
+ bounds: Box;
133
+ nodes: ArchNode[];
134
+ edges: ArchEdge[];
135
+ }
136
+
137
+ export interface ModelFile {
138
+ path: string;
139
+ text: string;
140
+ }
141
+
142
+ export interface HashedFile {
143
+ path: string;
144
+ sha256: string;
145
+ }
146
+
147
+ export type ModelRule = "model" | "no-specification" | "home" | "views";
148
+
149
+ export interface ModelProblem {
150
+ rule: ModelRule;
151
+ path: string;
152
+ line: number;
153
+ message: string;
154
+ }
155
+
156
+ export interface LayoutOptions {
157
+ /** The org's files the model is written against (specification, org elements). With a base, a model writes no specification. */
158
+ base?: ModelFile[];
159
+ /** The system a model may only extend: every element it adds must have an id inside it (`platform.tooling.x`). */
160
+ system?: string;
161
+ /** The view ids to return, in this order; each must exist. Default: every view LikeC4 does not add by itself (not the implicit `index`), the containers view for a C4. */
162
+ views?: string[];
163
+ }
164
+
165
+ export interface Layout {
166
+ schema: "krizaka.layout/1";
167
+ tool: { name: "@krizaka/architecture"; likec4: string };
168
+ /** The sha256 of every source file: the model's and the base's. */
169
+ sources: { model: HashedFile[]; base: HashedFile[] };
170
+ /** The check's verdict: `ok` (a refused model throws), the system it was checked against, the elements the model adds. */
171
+ check: { status: "ok"; system: string | null; errors: []; elements: string[] };
172
+ views: ArchView[];
173
+ }
174
+
175
+ export const LAYOUT_SCHEMA: "krizaka.layout/1";
176
+ export const RULES: Readonly<Record<"model" | "specification" | "home" | "views", ModelRule>>;
177
+
178
+ /** A model the check refuses. `rule` is the first rule that failed; `problems` lists every one. */
179
+ export class ArchitectureModelError extends Error {
180
+ readonly rule: ModelRule;
181
+ readonly problems: ModelProblem[];
182
+ constructor(problems: ModelProblem[]);
183
+ }
184
+
185
+ /**
186
+ * Check a LikeC4 model with the org's rules and lay its views out, at build time. Deterministic: the same sources give the
187
+ * same layout. Takes a LikeC4 text, a list of files, or the C4 `buildC4` returns (its containers view, no hand-written model).
188
+ * @throws {ArchitectureModelError}
189
+ */
190
+ export function layoutViews(model: string | ModelFile[] | C4, options?: LayoutOptions): Promise<Layout>;
191
+ /** The LikeC4 files of a C4's containers level (a specification, the containers, their relations, a `containers` view). */
192
+ export function modelOfC4(c4: C4): ModelFile[];
package/src/index.mjs CHANGED
@@ -1,3 +1,5 @@
1
1
  export { buildC4, buildC4FromFiles, SCHEMA } from "./c4.mjs";
2
+ export { ArchitectureModelError, LAYOUT_SCHEMA, layoutViews, RULES } from "./layout.mjs";
3
+ export { modelOfC4 } from "./model.mjs";
2
4
  export { toText } from "./text.mjs";
3
5
  export { baseVersion, globMatches, isOrgPackage, unitsOf } from "./units.mjs";
@@ -0,0 +1,57 @@
1
+ // krizaka-architecture layout <model.c4 | repo-path> [--out views.json] [--base file.c4]... [--system id] [--view id]...
2
+ // A .c4 file is checked and laid out; a directory is read with buildC4 and its containers view is laid out.
3
+ import { readFileSync, statSync, writeFileSync } from "node:fs";
4
+ import { basename, resolve } from "node:path";
5
+
6
+ import { buildC4 } from "./c4.mjs";
7
+ import { ArchitectureModelError, layoutViews } from "./layout.mjs";
8
+
9
+ const USAGE =
10
+ "usage: krizaka-architecture layout <model.c4 | repo-path> [--out views.json] [--base file.c4]... [--system id] [--view id]...";
11
+
12
+ /** Every value of a repeatable flag (`--base a --base b`), a single one for the others. */
13
+ function valuesOf(args, name) {
14
+ const out = [];
15
+ args.forEach((a, i) => {
16
+ if (a === `--${name}` && args[i + 1] && !args[i + 1].startsWith("--")) out.push(args[i + 1]);
17
+ });
18
+ return out;
19
+ }
20
+
21
+ /** Runs the subcommand; returns the exit code. */
22
+ export async function runLayout(args, { stdout = process.stdout, stderr = process.stderr } = {}) {
23
+ const flagValues = new Set(["out", "base", "system", "view"].flatMap((n) => valuesOf(args, n)));
24
+ const input = args.find((a) => !a.startsWith("--") && !flagValues.has(a));
25
+ if (!input) {
26
+ stderr.write(`${USAGE}\n`);
27
+ return 2;
28
+ }
29
+ const path = resolve(input);
30
+ let model;
31
+ try {
32
+ model = statSync(path).isDirectory() ? buildC4(path) : [{ path: basename(path), text: readFileSync(path, "utf8") }];
33
+ } catch {
34
+ stderr.write(`${USAGE}\n`);
35
+ return 2;
36
+ }
37
+ const base = valuesOf(args, "base").map((f) => ({ path: basename(f), text: readFileSync(resolve(f), "utf8") }));
38
+ const views = valuesOf(args, "view");
39
+ try {
40
+ const layout = await layoutViews(model, {
41
+ base,
42
+ system: valuesOf(args, "system")[0],
43
+ views: views.length ? views : undefined,
44
+ });
45
+ const json = `${JSON.stringify(layout, null, 2)}\n`;
46
+ const [out] = valuesOf(args, "out");
47
+ if (out) {
48
+ writeFileSync(resolve(out), json);
49
+ stdout.write(`${layout.views.length} view(s), check ${layout.check.status} -> ${out}\n`);
50
+ } else stdout.write(json);
51
+ return 0;
52
+ } catch (error) {
53
+ if (!(error instanceof ArchitectureModelError)) throw error;
54
+ stderr.write(`${error.message}\n`);
55
+ return 1;
56
+ }
57
+ }
package/src/layout.mjs ADDED
@@ -0,0 +1,192 @@
1
+ // Build-time layout of LikeC4 views (krizaka-internal#3671). A model is checked with the org's rules and laid out with
2
+ // LikeC4's own parser and Graphviz; what comes back is the geometry a drawing needs (`ArchView`), the hashes of the sources
3
+ // and the check's verdict. Deterministic: the same sources give the same JSON. Needs no network and no settings.
4
+ import { createHash } from "node:crypto";
5
+
6
+ import { fromSources } from "@likec4/language-services/node";
7
+
8
+ import { CONTAINERS_VIEW, isC4, modelOfC4 } from "./model.mjs";
9
+
10
+ export const LAYOUT_SCHEMA = "krizaka.layout/1";
11
+
12
+ /** The rules a model is checked against; an `ArchitectureModelError` names the one that failed. */
13
+ export const RULES = Object.freeze({
14
+ model: "model",
15
+ specification: "no-specification",
16
+ home: "home",
17
+ views: "views",
18
+ });
19
+
20
+ const describe = (p) => " " + p.path + ":" + p.line + " [" + p.rule + "] " + p.message;
21
+
22
+ /** A model the check refuses: `rule` is the first rule that failed, `problems` lists every one. */
23
+ export class ArchitectureModelError extends Error {
24
+ constructor(problems) {
25
+ super(`the architecture model is refused (${problems[0].rule}):\n${problems.map(describe).join("\n")}`);
26
+ this.name = "ArchitectureModelError";
27
+ this.rule = problems[0].rule;
28
+ this.problems = problems;
29
+ }
30
+ }
31
+
32
+ const sha256 = (text) => createHash("sha256").update(text).digest("hex");
33
+ const byString = (a, b) => Number(a > b) - Number(a < b);
34
+ const byPath = (a, b) => Number(a.path > b.path) - Number(a.path < b.path);
35
+ /** LikeC4 breaks a long label with a newline for its own drawing; a page wraps words itself. */
36
+ const flat = (s) =>
37
+ s == null
38
+ ? null
39
+ : String(s)
40
+ .split("\n")
41
+ .map((line) => line.trim())
42
+ .join(" ");
43
+ const textOf = (d) => flat(typeof d === "string" ? d : (d?.txt ?? null));
44
+ const stepOf = (id) => {
45
+ const [, n] = id.match(/^step-(\d+)$/) ?? [];
46
+ return n === undefined ? null : Number(n);
47
+ };
48
+ const MODEL_ROOT = "model/";
49
+ const BASE_ROOT = "base/";
50
+
51
+ /** One laid-out LikeC4 view as the drawing needs it. */
52
+ export function viewOf(v) {
53
+ return {
54
+ id: v.id,
55
+ title: v.title,
56
+ dynamic: v._type === "dynamic",
57
+ bounds: v.bounds,
58
+ nodes: v.nodes.map((n) => ({
59
+ id: n.id,
60
+ parent: n.parent ?? null,
61
+ kind: n.kind,
62
+ shape: n.shape,
63
+ title: flat(n.title),
64
+ technology: flat(n.technology),
65
+ description: textOf(n.description),
66
+ compound: (n.children ?? []).length > 0,
67
+ x: Math.round(n.x),
68
+ y: Math.round(n.y),
69
+ width: Math.round(n.width),
70
+ height: Math.round(n.height),
71
+ })),
72
+ edges: v.edges.map((e) => ({
73
+ id: e.id,
74
+ source: e.source,
75
+ target: e.target,
76
+ label: flat(e.label),
77
+ points: e.points.map(([x, y]) => [Math.round(x), Math.round(y)]),
78
+ labelBBox: e.labelBBox ?? null,
79
+ step: stepOf(e.id),
80
+ back: e.dir === "back",
81
+ })),
82
+ };
83
+ }
84
+
85
+ const withHash = (files) => files.map(({ path, text }) => ({ path, text, sha256: sha256(text) })).sort(byPath);
86
+ const virtualFiles = (files, root) => files.map((f) => [`${root}${f.path}`, f.text]);
87
+
88
+ /** Parse virtual files; run `run` on the LikeC4 instance, always disposed. */
89
+ async function withModel(files, run) {
90
+ const likec4 = await fromSources(Object.fromEntries(files));
91
+ try {
92
+ return await run(likec4);
93
+ } finally {
94
+ await likec4.dispose();
95
+ }
96
+ }
97
+
98
+ const problemOf = (rule, path, line, message) => ({ rule, path, line, message });
99
+
100
+ /** The sources as `{ path, text }` lists: a text, a list of files or a C4 built from code. */
101
+ function sourcesOf(model) {
102
+ if (typeof model === "string") return [{ path: "model.c4", text: model }];
103
+ if (isC4(model)) return modelOfC4(model);
104
+ if (Array.isArray(model)) return model;
105
+ throw new TypeError("layoutViews takes a LikeC4 text, a list of { path, text } or a C4 from buildC4");
106
+ }
107
+
108
+ /**
109
+ * Check a LikeC4 model with the org's rules and lay its views out.
110
+ *
111
+ * @param model a LikeC4 text, `[{ path, text }]`, or the C4 `buildC4` returns (its containers view is drawn)
112
+ * @param options `base`: the org's files the model is written against (`specification.c4`, `org.c4`), a model then writes
113
+ * no specification of its own; `system`: the id of the system a model may only extend (every element it adds lives inside);
114
+ * `views`: the view ids to return, in this order (each must exist), default all but LikeC4's implicit `index`
115
+ * @throws {ArchitectureModelError} when a rule fails; `rule` and `problems` say which
116
+ */
117
+ export async function layoutViews(model, options = {}) {
118
+ const base = withHash(options.base ?? []);
119
+ const files = withHash(sourcesOf(model));
120
+ const wanted = options.views ?? (isC4(model) ? [CONTAINERS_VIEW] : null);
121
+ const system = options.system ?? null;
122
+ const known = system && base.length ? await elementIds(base) : new Set();
123
+
124
+ const { problems, views, elements } = await withModel(
125
+ [...virtualFiles(base, BASE_ROOT), ...virtualFiles(files, MODEL_ROOT)],
126
+ async (likec4) => {
127
+ const found = [];
128
+ for (const e of likec4.getErrors()) {
129
+ const path = String(e.sourceFsPath ?? "").replace(/^\/workspace\//, "");
130
+ found.push(problemOf(RULES.model, path, e.line ?? 1, e.message));
131
+ }
132
+ if (base.length) {
133
+ for (const doc of likec4.langium.shared.workspace.LangiumDocuments.all.toArray()) {
134
+ if (
135
+ doc.uri.path.startsWith(`/workspace/${MODEL_ROOT}`) &&
136
+ (doc.parseResult.value.specifications ?? []).length
137
+ )
138
+ found.push(
139
+ problemOf(
140
+ RULES.specification,
141
+ doc.uri.path.replace("/workspace/", ""),
142
+ 1,
143
+ "a model writes no specification: the org's own is in its base",
144
+ ),
145
+ );
146
+ }
147
+ }
148
+ if (found.length) return { problems: found, views: [], elements: [] };
149
+ const own = [...(await likec4.computedModel()).elements()]
150
+ .map((e) => e.id)
151
+ .filter((id) => !known.has(id))
152
+ .sort(byString);
153
+ if (system)
154
+ for (const id of own.filter((x) => !x.startsWith(`${system}.`)))
155
+ found.push(
156
+ problemOf(
157
+ RULES.home,
158
+ `${MODEL_ROOT}${files[0]?.path ?? ""}`,
159
+ 1,
160
+ `« ${id} » is outside the system ${system}: a model only extends its own system`,
161
+ ),
162
+ );
163
+ return { problems: found, views: found.length ? [] : await likec4.diagrams(), elements: own };
164
+ },
165
+ );
166
+ // LikeC4 adds an implicit landscape view, `index`; it is returned only when asked for by name.
167
+ const laid = views.filter((v) => v.id !== "index" || wanted?.includes("index")).map(viewOf);
168
+ const absent = (wanted ?? []).filter((id) => !laid.some((v) => v.id === id));
169
+ if (!problems.length && absent.length)
170
+ problems.push(problemOf(RULES.views, files[0]?.path ?? "", 1, `the model has no view ${absent.join(", ")}`));
171
+ if (problems.length) throw new ArchitectureModelError(problems);
172
+
173
+ const likec4Version = (await import("@likec4/language-services/package.json", { with: { type: "json" } })).default
174
+ .version;
175
+ return {
176
+ schema: LAYOUT_SCHEMA,
177
+ tool: { name: "@krizaka/architecture", likec4: likec4Version },
178
+ sources: {
179
+ model: files.map(({ path, sha256: hash }) => ({ path, sha256: hash })),
180
+ base: base.map(({ path, sha256: hash }) => ({ path, sha256: hash })),
181
+ },
182
+ check: { status: "ok", system, errors: [], elements },
183
+ views: wanted ? wanted.map((id) => laid.find((v) => v.id === id)) : laid,
184
+ };
185
+ }
186
+
187
+ async function elementIds(base) {
188
+ return withModel(
189
+ virtualFiles(base, BASE_ROOT),
190
+ async (likec4) => new Set([...(await likec4.computedModel()).elements()].map((e) => e.id)),
191
+ );
192
+ }
package/src/model.mjs ADDED
@@ -0,0 +1,49 @@
1
+ // The LikeC4 model of a C4 built from code (`buildC4`): a specification, the containers as elements, the relations
2
+ // between them and one view, `containers`, so a repository gets its drawing without a hand-written model. Pure text out,
3
+ // deterministic: ids are positions in the sorted node list, never the package names (which are not identifiers).
4
+ import { SCHEMA } from "./c4.mjs";
5
+
6
+ export const CONTAINERS_VIEW = "containers";
7
+
8
+ const KINDS = ["app", "library", "module", "external"];
9
+ const escaped = (text) => String(text).replace(/[\\']/g, (c) => "\\" + c);
10
+ const quote = (text) => `'${escaped(text)}'`;
11
+ const firstSentence = (text) => {
12
+ const flat = String(text ?? "")
13
+ .replace(/\s+/g, " ")
14
+ .trim();
15
+ const end = flat.search(/[.!?](\s|$)/);
16
+ return end < 0 ? flat : flat.slice(0, end + 1);
17
+ };
18
+
19
+ /** Is this value a C4 as `buildC4` returns it? */
20
+ export const isC4 = (value) => typeof value === "object" && value !== null && value.schema === SCHEMA;
21
+
22
+ /** The LikeC4 text of the containers level of a C4: `[{ path, text }]`, one file. */
23
+ export function modelOfC4(c4) {
24
+ const level = c4.levels.containers;
25
+ const ids = new Map(level.nodes.map((n, i) => [n.id, `c${i}`]));
26
+ const lines = ["specification {", ...KINDS.map((k) => ` element ${k}`), "}", "model {"];
27
+ for (const n of level.nodes) {
28
+ const kind = KINDS.includes(n.kind) ? n.kind : "module";
29
+ lines.push(` ${ids.get(n.id)} = ${kind} ${quote(n.name)} {`);
30
+ const description = firstSentence(n.description);
31
+ if (description) lines.push(` description ${quote(description)}`);
32
+ if (n.technology) lines.push(` technology ${quote(n.technology)}`);
33
+ lines.push(" }");
34
+ }
35
+ for (const e of level.edges) {
36
+ if (ids.has(e.from) && ids.has(e.to)) lines.push(` ${ids.get(e.from)} -> ${ids.get(e.to)} ${quote(e.label)}`);
37
+ }
38
+ lines.push(
39
+ "}",
40
+ "views {",
41
+ ` view ${CONTAINERS_VIEW} {`,
42
+ ` title ${quote(c4.repo + " · containers")}`,
43
+ " include *",
44
+ " }",
45
+ "}",
46
+ "",
47
+ );
48
+ return [{ path: `${c4.repo}.c4`, text: lines.join("\n") }];
49
+ }