@diagc/cli 0.8.0 → 0.10.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/assets/studio/assets/{index-D4Fp9bp2.css → index-Csx5rLJC.css} +1 -1
- package/assets/studio/assets/index-DL_lrezG.js +109 -0
- package/assets/studio/index.html +2 -2
- package/assets/viewer/index.html +33 -33
- package/dist/cli.d.ts +15 -0
- package/dist/cli.js +148 -4
- package/dist/compile.d.ts +8 -2
- package/dist/compile.js +12 -3
- package/dist/diff.d.ts +61 -0
- package/dist/diff.js +215 -0
- package/dist/git-ref.d.ts +17 -0
- package/dist/git-ref.js +72 -0
- package/dist/lint.d.ts +14 -0
- package/dist/lint.js +27 -0
- package/dist/publish/publish.d.ts +11 -0
- package/dist/publish/publish.js +34 -26
- package/package.json +2 -2
- package/assets/studio/assets/index-DrCLMh6d.js +0 -109
package/dist/cli.d.ts
CHANGED
|
@@ -2,10 +2,18 @@ interface Args {
|
|
|
2
2
|
command: string;
|
|
3
3
|
files: string[];
|
|
4
4
|
out: string;
|
|
5
|
+
/** `--out` was passed: diff only defaults its own directory when it was not */
|
|
6
|
+
outGiven: boolean;
|
|
5
7
|
images: boolean;
|
|
6
8
|
updateIncludes: boolean;
|
|
9
|
+
/** `--json`: lint's findings as one JSON array on stdout */
|
|
10
|
+
json: boolean;
|
|
7
11
|
/** `--link`: validated here, so a bad address fails before anything is compiled */
|
|
8
12
|
link?: string;
|
|
13
|
+
/** diff `--image-url`: a URL template for summary.md's images, `{path}` per PNG */
|
|
14
|
+
imageUrl?: string;
|
|
15
|
+
/** diff `--labels before,after`: names for the two sides in place of the refs */
|
|
16
|
+
labels?: [string, string];
|
|
9
17
|
}
|
|
10
18
|
/** Parse argv into command + flags. Unknown flags (anything `--…` that is not
|
|
11
19
|
* recognized) are an error rather than being silently treated as a file path,
|
|
@@ -25,4 +33,11 @@ export declare class UnknownFlagError extends Error {
|
|
|
25
33
|
export declare class BadFlagValueError extends Error {
|
|
26
34
|
constructor(flag: string, why: string);
|
|
27
35
|
}
|
|
36
|
+
/** `A..B` or `A` (against the working tree). */
|
|
37
|
+
export declare function parseRange(range: string): {
|
|
38
|
+
from: string;
|
|
39
|
+
to?: string;
|
|
40
|
+
};
|
|
41
|
+
/** A ref as a directory name: `v1.0..feature/x` -> `v1.0..feature-x`. */
|
|
42
|
+
export declare function diffOutDir(from: string, to: string | undefined): string;
|
|
28
43
|
export {};
|
package/dist/cli.js
CHANGED
|
@@ -25,7 +25,10 @@ import { fileURLToPath } from 'node:url';
|
|
|
25
25
|
import fg from 'fast-glob';
|
|
26
26
|
import { errMessage } from '@diagc/core';
|
|
27
27
|
import { compileFile } from './compile.js';
|
|
28
|
+
import { compareDiagramSets, formatDiffSummary, loadDiagramSet, writeDiffPages } from './diff.js';
|
|
29
|
+
import { checkoutDiagrams } from './git-ref.js';
|
|
28
30
|
import { ejectDiagram } from './eject.js';
|
|
31
|
+
import { formatLintReport, lintFile } from './lint.js';
|
|
29
32
|
import { findHome, homePaths } from './home.js';
|
|
30
33
|
import { resolveInclude } from './includes.js';
|
|
31
34
|
import { snapshotSession } from './snapshots.js';
|
|
@@ -33,19 +36,26 @@ import { formatCompileEvent, startWatch } from './watch.js';
|
|
|
33
36
|
import { galleryLink } from './publish/gallery.js';
|
|
34
37
|
import { publishDiagrams } from './publish/publish.js';
|
|
35
38
|
import { runStudio } from './studio.js';
|
|
36
|
-
const USAGE = `Usage: diagc <compile|watch|publish|studio|eject> [files...] [--out dir]
|
|
39
|
+
const USAGE = `Usage: diagc <compile|lint|watch|publish|studio|eject|diff> [files...] [--out dir]
|
|
37
40
|
|
|
38
41
|
Commands:
|
|
39
42
|
compile Compile *.diagram.{ts,json} sources into overlay artifacts once
|
|
43
|
+
lint Report suspicious diagrams (typos, duplicates, unused or undrawn parts); exit 1 on any
|
|
40
44
|
watch Recompile — and live-recompile — a directory of sources
|
|
41
45
|
publish Compile and render an HTML/PNG site under .diagrams/
|
|
42
46
|
studio Run the visual studio against the current directory
|
|
43
47
|
eject Promote a JSON diagram to a generated TypeScript source (verified)
|
|
48
|
+
diff diff <from>[..<to>] [names...]: what changed in the diagrams between two git
|
|
49
|
+
refs (or a ref and the working tree), with before/after pages and PNGs
|
|
44
50
|
|
|
45
51
|
Options:
|
|
46
|
-
--out dir Artifact output directory (default .diagrams/.artifacts
|
|
47
|
-
|
|
52
|
+
--out dir Artifact output directory (default .diagrams/.artifacts;
|
|
53
|
+
diff: .diagrams/diff/<from>..<to>)
|
|
54
|
+
--no-images Publish (or diff) HTML without rendering PNG images
|
|
48
55
|
--link url Publish with a link to url in the index header
|
|
56
|
+
--json lint: print the findings as a JSON array; diff: the changes as JSON
|
|
57
|
+
--labels a,b diff: name the two sides (default: the refs)
|
|
58
|
+
--image-url t diff: summary.md's image links as t, {path} standing for each PNG
|
|
49
59
|
--update-includes Refetch remote includes and rewrite the snapshot lock
|
|
50
60
|
--help, -h Show this help and exit
|
|
51
61
|
`;
|
|
@@ -56,14 +66,19 @@ export function parseArgs(argv) {
|
|
|
56
66
|
let command = 'compile';
|
|
57
67
|
const files = [];
|
|
58
68
|
let out = '.diagrams/.artifacts';
|
|
69
|
+
let outGiven = false;
|
|
59
70
|
let images = true;
|
|
60
71
|
let updateIncludes = false;
|
|
72
|
+
let json = false;
|
|
61
73
|
let link;
|
|
74
|
+
let imageUrl;
|
|
75
|
+
let labels;
|
|
62
76
|
let commandSeen = false;
|
|
63
77
|
for (let i = 0; i < argv.length; i++) {
|
|
64
78
|
const arg = argv[i];
|
|
65
79
|
if (arg === '--out') {
|
|
66
80
|
out = argv[++i] ?? out;
|
|
81
|
+
outGiven = true;
|
|
67
82
|
continue;
|
|
68
83
|
}
|
|
69
84
|
if (arg === '--no-images') {
|
|
@@ -74,6 +89,24 @@ export function parseArgs(argv) {
|
|
|
74
89
|
updateIncludes = true;
|
|
75
90
|
continue;
|
|
76
91
|
}
|
|
92
|
+
if (arg === '--json') {
|
|
93
|
+
json = true;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (arg === '--image-url') {
|
|
97
|
+
const value = argv[++i] ?? '';
|
|
98
|
+
if (!value.includes('{path}'))
|
|
99
|
+
throw new BadFlagValueError('--image-url', 'needs a {path} placeholder, e.g. https://host/pr-1/{path}');
|
|
100
|
+
imageUrl = value;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (arg === '--labels') {
|
|
104
|
+
const parts = (argv[++i] ?? '').split(',');
|
|
105
|
+
if (parts.length !== 2 || parts.some((p) => p.trim() === ''))
|
|
106
|
+
throw new BadFlagValueError('--labels', 'takes two names, before and after: --labels main,#12');
|
|
107
|
+
labels = [parts[0].trim(), parts[1].trim()];
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
77
110
|
if (arg === '--link') {
|
|
78
111
|
// No fallback for a missing value, unlike --out: there is no default address, and
|
|
79
112
|
// the URL check is also what stops the next flag being swallowed as one.
|
|
@@ -101,7 +134,18 @@ export function parseArgs(argv) {
|
|
|
101
134
|
files.push(arg);
|
|
102
135
|
}
|
|
103
136
|
}
|
|
104
|
-
return {
|
|
137
|
+
return {
|
|
138
|
+
command,
|
|
139
|
+
files,
|
|
140
|
+
out,
|
|
141
|
+
outGiven,
|
|
142
|
+
images,
|
|
143
|
+
updateIncludes,
|
|
144
|
+
json,
|
|
145
|
+
...(link !== undefined ? { link } : {}),
|
|
146
|
+
...(imageUrl !== undefined ? { imageUrl } : {}),
|
|
147
|
+
...(labels !== undefined ? { labels } : {}),
|
|
148
|
+
};
|
|
105
149
|
}
|
|
106
150
|
/** Thrown by {@link parseArgs} for `--help`/`-h`; `main` prints usage and exits 0. */
|
|
107
151
|
export class HelpRequested extends Error {
|
|
@@ -174,6 +218,19 @@ async function main() {
|
|
|
174
218
|
await snap.prune();
|
|
175
219
|
process.exit(failed ? 1 : 0);
|
|
176
220
|
}
|
|
221
|
+
else if (args.command === 'lint') {
|
|
222
|
+
const files = args.files.length > 0 ? args.files : await fg('.diagrams/src/**/*.diagram.{ts,json}');
|
|
223
|
+
const reports = [];
|
|
224
|
+
for (const file of files) {
|
|
225
|
+
reports.push(...(await lintFile(file, { rootDir: '.diagrams/src', coreEntry: home.coreEntry, resolver: snap.resolver })));
|
|
226
|
+
}
|
|
227
|
+
if (args.json)
|
|
228
|
+
console.log(JSON.stringify(reports, null, 2));
|
|
229
|
+
else
|
|
230
|
+
for (const r of reports)
|
|
231
|
+
console.log(formatLintReport(r));
|
|
232
|
+
process.exit(reports.length > 0 ? 1 : 0);
|
|
233
|
+
}
|
|
177
234
|
else if (args.command === 'watch') {
|
|
178
235
|
// Always locked, independent of args.updateIncludes: watch is a long-running
|
|
179
236
|
// live loop with no point at which "refetch and rewrite the lock" makes
|
|
@@ -284,12 +341,99 @@ async function main() {
|
|
|
284
341
|
process.exit(1);
|
|
285
342
|
}
|
|
286
343
|
}
|
|
344
|
+
else if (args.command === 'diff') {
|
|
345
|
+
process.exit(await runDiff(args, home));
|
|
346
|
+
}
|
|
287
347
|
else {
|
|
288
348
|
console.error(`diagc: Unknown command '${args.command}'.`);
|
|
289
349
|
console.error(USAGE);
|
|
290
350
|
process.exit(1);
|
|
291
351
|
}
|
|
292
352
|
}
|
|
353
|
+
/** `A..B` or `A` (against the working tree). */
|
|
354
|
+
export function parseRange(range) {
|
|
355
|
+
const at = range.indexOf('..');
|
|
356
|
+
if (at === -1)
|
|
357
|
+
return { from: range };
|
|
358
|
+
const from = range.slice(0, at);
|
|
359
|
+
const to = range.slice(at + 2);
|
|
360
|
+
if (from === '' || to === '' || to.startsWith('.'))
|
|
361
|
+
throw new Error(`'${range}' is not a range: write <from>..<to>, or one ref to compare with the working tree`);
|
|
362
|
+
return { from, to };
|
|
363
|
+
}
|
|
364
|
+
/** A ref as a directory name: `v1.0..feature/x` -> `v1.0..feature-x`. */
|
|
365
|
+
export function diffOutDir(from, to) {
|
|
366
|
+
const safe = (s) => s.replace(/[^A-Za-z0-9._-]+/g, '-');
|
|
367
|
+
return path.join('.diagrams', 'diff', `${safe(from)}..${to !== undefined ? safe(to) : 'working-tree'}`);
|
|
368
|
+
}
|
|
369
|
+
async function runDiff(args, home) {
|
|
370
|
+
const range = args.files[0];
|
|
371
|
+
if (range === undefined) {
|
|
372
|
+
console.error('diagc: diff needs a git ref (diff v1.0) or a range (diff v1.0..v2.0).');
|
|
373
|
+
console.error(USAGE);
|
|
374
|
+
return 1;
|
|
375
|
+
}
|
|
376
|
+
const checkouts = [];
|
|
377
|
+
try {
|
|
378
|
+
const { from, to } = parseRange(range);
|
|
379
|
+
const before = await checkoutDiagrams(from, process.cwd());
|
|
380
|
+
checkouts.push(before);
|
|
381
|
+
let afterDir = '.diagrams';
|
|
382
|
+
if (to !== undefined) {
|
|
383
|
+
const after = await checkoutDiagrams(to, process.cwd());
|
|
384
|
+
checkouts.push(after);
|
|
385
|
+
afterDir = after.diagramsDir;
|
|
386
|
+
}
|
|
387
|
+
const fromLabel = args.labels?.[0] ?? from;
|
|
388
|
+
const toLabel = args.labels?.[1] ?? to ?? 'working tree';
|
|
389
|
+
const beforeSet = await loadDiagramSet(fromLabel, before.diagramsDir, home.coreEntry);
|
|
390
|
+
const afterSet = await loadDiagramSet(toLabel, afterDir, home.coreEntry);
|
|
391
|
+
const diffs = compareDiagramSets(beforeSet, afterSet, args.files.slice(1));
|
|
392
|
+
if (args.json) {
|
|
393
|
+
console.log(JSON.stringify({ from: fromLabel, to: toLabel, diagrams: diffs.map(({ before: _b, after: _a, ...rest }) => rest) }, null, 2));
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
console.log(formatDiffSummary(diffs, fromLabel, toLabel));
|
|
397
|
+
}
|
|
398
|
+
if (!diffs.some((d) => d.status === 'added' || d.status === 'removed' || d.status === 'changed'))
|
|
399
|
+
return 0;
|
|
400
|
+
if (!existsSync(home.viewerShell)) {
|
|
401
|
+
console.error('viewer shell not available — writing the summary only (see `diagc publish` for how to build it).');
|
|
402
|
+
return 0;
|
|
403
|
+
}
|
|
404
|
+
let renderPng;
|
|
405
|
+
if (args.images) {
|
|
406
|
+
const snapshot = await import('./publish/snapshot.js');
|
|
407
|
+
if (snapshot.findChrome() === undefined)
|
|
408
|
+
console.error('No Chrome found — writing HTML only; install Chrome / set CHROME_PATH, or use --no-images.');
|
|
409
|
+
else
|
|
410
|
+
renderPng = snapshot.renderPng;
|
|
411
|
+
}
|
|
412
|
+
const outDir = args.outGiven ? args.out : diffOutDir(from, to);
|
|
413
|
+
const res = await writeDiffPages(diffs, {
|
|
414
|
+
outDir,
|
|
415
|
+
shellPath: home.viewerShell,
|
|
416
|
+
libraryDir: home.libraryDir,
|
|
417
|
+
before: beforeSet,
|
|
418
|
+
after: afterSet,
|
|
419
|
+
...(renderPng !== undefined ? { renderPng } : {}),
|
|
420
|
+
...(args.imageUrl !== undefined ? { imageUrl: args.imageUrl } : {}),
|
|
421
|
+
});
|
|
422
|
+
// stderr, so `--json` output stays parseable on stdout
|
|
423
|
+
console.error(`✓ ${res.pages.length} page(s)${res.images.length > 0 ? `, ${res.images.length} image(s)` : ''} -> ${outDir}`);
|
|
424
|
+
console.error(`✓ side by side -> ${res.index}`);
|
|
425
|
+
console.error(`✓ for an ADR -> ${res.summary}`);
|
|
426
|
+
return 0;
|
|
427
|
+
}
|
|
428
|
+
catch (e) {
|
|
429
|
+
console.error(`diagc: ${errMessage(e)}`);
|
|
430
|
+
return 1;
|
|
431
|
+
}
|
|
432
|
+
finally {
|
|
433
|
+
for (const c of checkouts)
|
|
434
|
+
await c.cleanup();
|
|
435
|
+
}
|
|
436
|
+
}
|
|
293
437
|
main().catch((e) => {
|
|
294
438
|
console.error(errMessage(e));
|
|
295
439
|
process.exit(1);
|
package/dist/compile.d.ts
CHANGED
|
@@ -4,8 +4,14 @@ import { type DiagramModel, type IncludeResolver } from '@diagc/core';
|
|
|
4
4
|
* its model — shape-guarded but not validated; callers own validation.
|
|
5
5
|
*/
|
|
6
6
|
export declare function executeDiagramTs(file: string, coreEntry?: string): Promise<DiagramModel>;
|
|
7
|
-
export
|
|
7
|
+
export interface LoadOptions {
|
|
8
8
|
rootDir?: string;
|
|
9
9
|
coreEntry?: string;
|
|
10
10
|
resolver?: IncludeResolver;
|
|
11
|
-
}
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Read a source, validate it, expand its includes and validate the result: the
|
|
14
|
+
* model `compile` writes and `lint` inspects. Throws on anything invalid.
|
|
15
|
+
*/
|
|
16
|
+
export declare function loadModel(file: string, opts?: LoadOptions): Promise<DiagramModel>;
|
|
17
|
+
export declare function compileFile(file: string, outDir: string, opts?: LoadOptions): Promise<string>;
|
package/dist/compile.js
CHANGED
|
@@ -54,7 +54,11 @@ function relativeSubdir(file, rootDir) {
|
|
|
54
54
|
const dir = path.dirname(rel);
|
|
55
55
|
return dir === '.' ? '' : dir;
|
|
56
56
|
}
|
|
57
|
-
|
|
57
|
+
/**
|
|
58
|
+
* Read a source, validate it, expand its includes and validate the result: the
|
|
59
|
+
* model `compile` writes and `lint` inspects. Throws on anything invalid.
|
|
60
|
+
*/
|
|
61
|
+
export async function loadModel(file, opts) {
|
|
58
62
|
const isJsonSource = file.endsWith('.diagram.json');
|
|
59
63
|
let model;
|
|
60
64
|
if (isJsonSource) {
|
|
@@ -97,8 +101,13 @@ export async function compileFile(file, outDir, opts) {
|
|
|
97
101
|
if (issues.length > 0)
|
|
98
102
|
throw new DiagramValidationError(issues);
|
|
99
103
|
}
|
|
100
|
-
|
|
101
|
-
|
|
104
|
+
return model;
|
|
105
|
+
}
|
|
106
|
+
export async function compileFile(file, outDir, opts) {
|
|
107
|
+
const model = await loadModel(file, opts);
|
|
108
|
+
// Sound but probably not what was meant (a fishbone cause on no bone, a typo'd
|
|
109
|
+
// type): say so, and compile anyway — the studio saves the same model without
|
|
110
|
+
// complaint. `diagc lint` is the strict reading of the same list.
|
|
102
111
|
for (const w of diagramWarnings(model))
|
|
103
112
|
console.warn(`${file}: ${w.message}`);
|
|
104
113
|
const base = path.basename(file).replace(/\.diagram\.(ts|json)$/, '');
|
package/dist/diff.d.ts
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { type DiagramModel, type Drawings, type LayoutOverlay, type ModelDiff } from '@diagc/core';
|
|
2
|
+
/** One diagram as a version of the repo had it: the compiled model plus the
|
|
3
|
+
* sidecars a picture of it needs. */
|
|
4
|
+
export interface DiagramVersion {
|
|
5
|
+
model: DiagramModel;
|
|
6
|
+
layout?: LayoutOverlay;
|
|
7
|
+
drawings?: Drawings;
|
|
8
|
+
}
|
|
9
|
+
/** Every diagram under one `.diagrams/` directory, by name (its path under
|
|
10
|
+
* `src/` without the extension — the names `publish` uses). */
|
|
11
|
+
export interface DiagramSet {
|
|
12
|
+
/** shown in the summary and on the pictures: a ref, or "working tree" */
|
|
13
|
+
label: string;
|
|
14
|
+
diagramsDir: string;
|
|
15
|
+
versions: Map<string, DiagramVersion>;
|
|
16
|
+
/** diagrams whose source did not compile at this version, with why */
|
|
17
|
+
errors: Map<string, string>;
|
|
18
|
+
}
|
|
19
|
+
export type DiagramDiffStatus = 'added' | 'removed' | 'changed' | 'unchanged' | 'error';
|
|
20
|
+
export interface DiagramDiff {
|
|
21
|
+
name: string;
|
|
22
|
+
status: DiagramDiffStatus;
|
|
23
|
+
before?: DiagramVersion;
|
|
24
|
+
after?: DiagramVersion;
|
|
25
|
+
/** against an empty model for an added or removed diagram, so the marks
|
|
26
|
+
* cover the whole picture the same way */
|
|
27
|
+
diff?: ModelDiff;
|
|
28
|
+
error?: string;
|
|
29
|
+
}
|
|
30
|
+
/** Compile every source under `diagramsDir/src` in memory — nothing is written. */
|
|
31
|
+
export declare function loadDiagramSet(label: string, diagramsDir: string, coreEntry?: string): Promise<DiagramSet>;
|
|
32
|
+
/** Pair the two sets by name. `names` narrows the result to those diagrams. */
|
|
33
|
+
export declare function compareDiagramSets(before: DiagramSet, after: DiagramSet, names?: readonly string[]): DiagramDiff[];
|
|
34
|
+
/** The change list for one diagram, one line each, `+`/`-`/`~` first. */
|
|
35
|
+
export declare function describeDiff(d: DiagramDiff): string[];
|
|
36
|
+
export declare function formatDiffSummary(diffs: readonly DiagramDiff[], from: string, to: string): string;
|
|
37
|
+
export interface DiffPagesOptions {
|
|
38
|
+
outDir: string;
|
|
39
|
+
shellPath: string;
|
|
40
|
+
libraryDir: string;
|
|
41
|
+
before: DiagramSet;
|
|
42
|
+
after: DiagramSet;
|
|
43
|
+
renderPng?: (htmlPath: string, pngPath: string) => Promise<void>;
|
|
44
|
+
/** where `summary.md`'s images will be served from, `{path}` standing for
|
|
45
|
+
* each PNG's path under `outDir` — for a summary posted somewhere else (a PR
|
|
46
|
+
* comment), where the relative links would not resolve */
|
|
47
|
+
imageUrl?: string;
|
|
48
|
+
}
|
|
49
|
+
export interface DiffPagesResult {
|
|
50
|
+
pages: string[];
|
|
51
|
+
images: string[];
|
|
52
|
+
index: string;
|
|
53
|
+
summary: string;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* A page per side of every diagram that changed — the same single-file viewer
|
|
57
|
+
* `publish` writes, with the changes outlined — plus a PNG of each when
|
|
58
|
+
* `renderPng` is given, an `index.html` showing the two sides next to each
|
|
59
|
+
* other, and a `summary.md` laid out to paste into an ADR.
|
|
60
|
+
*/
|
|
61
|
+
export declare function writeDiffPages(diffs: readonly DiagramDiff[], opts: DiffPagesOptions): Promise<DiffPagesResult>;
|
package/dist/diff.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import fg from 'fast-glob';
|
|
5
|
+
import { diffMarks, diffModels, errMessage, isDrawings, isEmptyDiff, } from '@diagc/core';
|
|
6
|
+
import { loadModel } from './compile.js';
|
|
7
|
+
import { inlineAssets } from './publish/publish.js';
|
|
8
|
+
import { stampHtml } from './publish/html.js';
|
|
9
|
+
const EMPTY = { version: 1, id: '', name: '', nodes: [], containment: [], relations: [], layers: [], planes: [] };
|
|
10
|
+
async function readJson(file) {
|
|
11
|
+
return existsSync(file) ? JSON.parse(await readFile(file, 'utf8')) : undefined;
|
|
12
|
+
}
|
|
13
|
+
/** Compile every source under `diagramsDir/src` in memory — nothing is written. */
|
|
14
|
+
export async function loadDiagramSet(label, diagramsDir, coreEntry) {
|
|
15
|
+
const srcDir = path.join(diagramsDir, 'src');
|
|
16
|
+
const versions = new Map();
|
|
17
|
+
const errors = new Map();
|
|
18
|
+
const files = existsSync(srcDir) ? await fg('**/*.diagram.{ts,json}', { cwd: srcDir }) : [];
|
|
19
|
+
for (const rel of files.sort()) {
|
|
20
|
+
const name = rel.replace(/\.diagram\.(ts|json)$/, '');
|
|
21
|
+
try {
|
|
22
|
+
const model = await loadModel(path.join(srcDir, rel), { rootDir: srcDir, ...(coreEntry !== undefined ? { coreEntry } : {}) });
|
|
23
|
+
const layout = (await readJson(path.join(srcDir, `${name}.layout.json`)));
|
|
24
|
+
const drawings = await readJson(path.join(srcDir, `${name}.drawings.json`));
|
|
25
|
+
versions.set(name, {
|
|
26
|
+
model,
|
|
27
|
+
...(layout !== undefined ? { layout } : {}),
|
|
28
|
+
...(drawings !== undefined && isDrawings(drawings) ? { drawings } : {}),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
catch (e) {
|
|
32
|
+
errors.set(name, errMessage(e));
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return { label, diagramsDir, versions, errors };
|
|
36
|
+
}
|
|
37
|
+
/** Pair the two sets by name. `names` narrows the result to those diagrams. */
|
|
38
|
+
export function compareDiagramSets(before, after, names = []) {
|
|
39
|
+
const all = new Set([...before.versions.keys(), ...before.errors.keys(), ...after.versions.keys(), ...after.errors.keys()]);
|
|
40
|
+
const wanted = names.length > 0 ? names.filter((n) => all.has(n)) : [...all].sort();
|
|
41
|
+
return wanted.map((name) => {
|
|
42
|
+
const b = before.versions.get(name);
|
|
43
|
+
const a = after.versions.get(name);
|
|
44
|
+
const err = after.errors.get(name) ?? before.errors.get(name);
|
|
45
|
+
if (err !== undefined) {
|
|
46
|
+
const at = after.errors.has(name) ? after.label : before.label;
|
|
47
|
+
return { name, status: 'error', error: `does not compile at ${at}: ${err}` };
|
|
48
|
+
}
|
|
49
|
+
if (b === undefined)
|
|
50
|
+
return { name, status: 'added', after: a, diff: diffModels(EMPTY, a.model) };
|
|
51
|
+
if (a === undefined)
|
|
52
|
+
return { name, status: 'removed', before: b, diff: diffModels(b.model, EMPTY) };
|
|
53
|
+
const diff = diffModels(b.model, a.model);
|
|
54
|
+
return { name, status: isEmptyDiff(diff) ? 'unchanged' : 'changed', before: b, after: a, diff };
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
function nameIn(m, id) {
|
|
58
|
+
const n = m?.nodes.find((x) => x.id === id);
|
|
59
|
+
return n === undefined || n.name === '' ? id : n.name;
|
|
60
|
+
}
|
|
61
|
+
/** The change list for one diagram, one line each, `+`/`-`/`~` first. */
|
|
62
|
+
export function describeDiff(d) {
|
|
63
|
+
if (d.diff === undefined)
|
|
64
|
+
return [];
|
|
65
|
+
if (d.status === 'added')
|
|
66
|
+
return [`+ new diagram: ${d.after.model.name} (${d.diff.nodes.added.length} nodes, ${d.diff.relations.added.length} relations)`];
|
|
67
|
+
if (d.status === 'removed')
|
|
68
|
+
return [`- diagram removed: ${d.before.model.name}`];
|
|
69
|
+
const before = d.before?.model;
|
|
70
|
+
const after = d.after?.model;
|
|
71
|
+
const rel = (m, r) => `${nameIn(m, r.from)} -> ${nameIn(m, r.to)} (${r.kind}${r.label !== undefined && r.label !== '' ? `: ${r.label}` : ''})`;
|
|
72
|
+
const x = d.diff;
|
|
73
|
+
return [
|
|
74
|
+
...x.nodes.added.map((n) => `+ ${n.name !== '' ? n.name : n.id}${n.type !== undefined ? ` [${n.type}]` : ''}`),
|
|
75
|
+
...x.nodes.removed.map((n) => `- ${n.name !== '' ? n.name : n.id}${n.type !== undefined ? ` [${n.type}]` : ''}`),
|
|
76
|
+
...x.nodes.changed.map((n) => {
|
|
77
|
+
// A rename reads better as the two names than as the word "name".
|
|
78
|
+
const was = nameIn(before, n.id);
|
|
79
|
+
const now = nameIn(after, n.id);
|
|
80
|
+
const rest = n.fields.filter((f) => f !== 'name');
|
|
81
|
+
const head = n.fields.includes('name') ? `${was} -> ${now} (renamed)` : now;
|
|
82
|
+
return `~ ${head}${rest.length > 0 ? `: ${rest.join(', ')}` : ''}`;
|
|
83
|
+
}),
|
|
84
|
+
...x.relations.added.map((r) => `+ ${rel(after, r)}`),
|
|
85
|
+
...x.relations.removed.map((r) => `- ${rel(before, r)}`),
|
|
86
|
+
...x.relations.changed.map((r) => {
|
|
87
|
+
const now = after?.relations.find((y) => y.id === r.after);
|
|
88
|
+
return `~ ${now !== undefined ? rel(after, now) : r.after}: ${r.fields.join(', ')}`;
|
|
89
|
+
}),
|
|
90
|
+
...x.layers.added.map((id) => `+ layer ${id}`),
|
|
91
|
+
...x.layers.removed.map((id) => `- layer ${id}`),
|
|
92
|
+
...x.planes.added.map((id) => `+ plane ${id}`),
|
|
93
|
+
...x.planes.removed.map((id) => `- plane ${id}`),
|
|
94
|
+
];
|
|
95
|
+
}
|
|
96
|
+
export function formatDiffSummary(diffs, from, to) {
|
|
97
|
+
const lines = [`diagc diff ${from} -> ${to}`];
|
|
98
|
+
for (const d of diffs) {
|
|
99
|
+
if (d.status === 'unchanged')
|
|
100
|
+
continue;
|
|
101
|
+
if (d.status === 'error') {
|
|
102
|
+
lines.push(`! ${d.name}: ${d.error}`);
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
lines.push(`${d.name}:`);
|
|
106
|
+
for (const l of describeDiff(d))
|
|
107
|
+
lines.push(` ${l}`);
|
|
108
|
+
}
|
|
109
|
+
const changed = diffs.filter((d) => d.status !== 'unchanged' && d.status !== 'error').length;
|
|
110
|
+
const same = diffs.filter((d) => d.status === 'unchanged').length;
|
|
111
|
+
lines.push(changed === 0 ? `no diagram changed (${same} compared)` : `${changed} diagram(s) changed, ${same} unchanged`);
|
|
112
|
+
return lines.join('\n');
|
|
113
|
+
}
|
|
114
|
+
const escapeHtml = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
115
|
+
/**
|
|
116
|
+
* A page per side of every diagram that changed — the same single-file viewer
|
|
117
|
+
* `publish` writes, with the changes outlined — plus a PNG of each when
|
|
118
|
+
* `renderPng` is given, an `index.html` showing the two sides next to each
|
|
119
|
+
* other, and a `summary.md` laid out to paste into an ADR.
|
|
120
|
+
*/
|
|
121
|
+
export async function writeDiffPages(diffs, opts) {
|
|
122
|
+
const shell = await readFile(opts.shellPath, 'utf8');
|
|
123
|
+
await mkdir(opts.outDir, { recursive: true });
|
|
124
|
+
const caches = { before: new Map(), after: new Map() };
|
|
125
|
+
const pages = [];
|
|
126
|
+
const images = [];
|
|
127
|
+
const shown = diffs.filter((d) => d.status === 'added' || d.status === 'removed' || d.status === 'changed');
|
|
128
|
+
const files = new Map();
|
|
129
|
+
for (const d of shown) {
|
|
130
|
+
const entry = { png: opts.renderPng !== undefined };
|
|
131
|
+
for (const side of ['before', 'after']) {
|
|
132
|
+
const v = d[side];
|
|
133
|
+
if (v === undefined)
|
|
134
|
+
continue;
|
|
135
|
+
const set = opts[side];
|
|
136
|
+
const model = await inlineAssets(v.model, { libraryDir: opts.libraryDir, assetsDir: path.join(set.diagramsDir, 'src', 'assets') }, caches[side], `diagram "${d.name}" at ${set.label}`);
|
|
137
|
+
const rel = `${d.name}.${side}`;
|
|
138
|
+
const pagePath = path.join(opts.outDir, `${rel}.html`);
|
|
139
|
+
await mkdir(path.dirname(pagePath), { recursive: true });
|
|
140
|
+
await writeFile(pagePath, stampHtml(shell, {
|
|
141
|
+
model,
|
|
142
|
+
...(v.layout !== undefined ? { layout: v.layout } : {}),
|
|
143
|
+
...(v.drawings !== undefined ? { drawings: v.drawings } : {}),
|
|
144
|
+
diff: { marks: diffMarks(d.diff, side) },
|
|
145
|
+
}));
|
|
146
|
+
pages.push(pagePath);
|
|
147
|
+
entry[side] = rel;
|
|
148
|
+
if (opts.renderPng !== undefined) {
|
|
149
|
+
const pngPath = path.join(opts.outDir, `${rel}.png`);
|
|
150
|
+
await opts.renderPng(pagePath, pngPath);
|
|
151
|
+
images.push(pngPath);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
files.set(d.name, entry);
|
|
155
|
+
}
|
|
156
|
+
const from = opts.before.label;
|
|
157
|
+
const to = opts.after.label;
|
|
158
|
+
const index = path.join(opts.outDir, 'index.html');
|
|
159
|
+
await writeFile(index, indexHtml(shown, files, from, to));
|
|
160
|
+
const summary = path.join(opts.outDir, 'summary.md');
|
|
161
|
+
await writeFile(summary, summaryMarkdown(diffs, files, from, to, opts.imageUrl));
|
|
162
|
+
return { pages, images, index, summary };
|
|
163
|
+
}
|
|
164
|
+
// The frames load each page unfolded (`?export=1`, the PNG's own mode): side by
|
|
165
|
+
// side, the whole picture is the point. The headings link the interactive pages.
|
|
166
|
+
function indexHtml(shown, files, from, to) {
|
|
167
|
+
const side = (rel, label) => rel === undefined
|
|
168
|
+
? `<div class="side empty"><h3>${escapeHtml(label)}</h3><p>not present</p></div>`
|
|
169
|
+
: `<div class="side"><h3><a href="${escapeHtml(rel)}.html">${escapeHtml(label)}</a></h3><iframe src="${escapeHtml(rel)}.html?export=1" title="${escapeHtml(label)}"></iframe></div>`;
|
|
170
|
+
const sections = shown.map((d) => {
|
|
171
|
+
const f = files.get(d.name) ?? {};
|
|
172
|
+
const list = describeDiff(d).map((l) => `<li class="${l[0] === '+' ? 'add' : l[0] === '-' ? 'del' : 'chg'}">${escapeHtml(l)}</li>`).join('');
|
|
173
|
+
return `<section><h2>${escapeHtml(d.name)}</h2><ul>${list}</ul><div class="pair">${side(f.before, `Before · ${from}`)}${side(f.after, `After · ${to}`)}</div></section>`;
|
|
174
|
+
});
|
|
175
|
+
return `<!doctype html>
|
|
176
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
177
|
+
<title>Diagram diff ${escapeHtml(from)} → ${escapeHtml(to)}</title>
|
|
178
|
+
<style>
|
|
179
|
+
body { font: 14px/1.45 system-ui, sans-serif; margin: 0 auto; padding: 16px 24px 48px; max-width: 1800px; color: #1f2328; background: #fff; }
|
|
180
|
+
h1 { font-size: 20px; } h2 { font-size: 16px; margin: 32px 0 6px; } h3 { font-size: 13px; margin: 0 0 6px; color: #57606a; }
|
|
181
|
+
ul { margin: 0 0 12px; padding-left: 18px; font-family: ui-monospace, monospace; font-size: 12.5px; }
|
|
182
|
+
li.add { color: #16a34a; } li.del { color: #dc2626; } li.chg { color: #b45309; }
|
|
183
|
+
.key span { display: inline-block; margin-right: 14px; } .key i { display: inline-block; width: 12px; height: 12px; border: 3px solid; border-radius: 3px; vertical-align: -2px; margin-right: 4px; }
|
|
184
|
+
.pair { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
|
185
|
+
.side iframe { width: 100%; height: 70vh; border: 1px solid #d0d7de; border-radius: 6px; }
|
|
186
|
+
.side.empty p { height: 70vh; margin: 0; display: grid; place-items: center; border: 1px dashed #d0d7de; border-radius: 6px; color: #8c959f; }
|
|
187
|
+
@media (max-width: 900px) { .pair { grid-template-columns: 1fr; } }
|
|
188
|
+
</style></head><body>
|
|
189
|
+
<h1>Diagram diff · ${escapeHtml(from)} → ${escapeHtml(to)}</h1>
|
|
190
|
+
<p class="key"><span><i style="border-color:#16a34a"></i>added</span><span><i style="border-color:#dc2626;border-style:dashed"></i>removed</span><span><i style="border-color:#d97706"></i>changed</span><span><i style="border-color:#d97706;border-style:dashed"></i>holds a change (folded box, on the linked pages)</span></p>
|
|
191
|
+
${sections.length > 0 ? sections.join('\n') : '<p>No diagram changed.</p>'}
|
|
192
|
+
</body></html>
|
|
193
|
+
`;
|
|
194
|
+
}
|
|
195
|
+
function summaryMarkdown(diffs, files, from, to, imageUrl) {
|
|
196
|
+
const png = (rel) => (imageUrl !== undefined ? imageUrl.split('{path}').join(`${rel}.png`) : `${rel}.png`);
|
|
197
|
+
const out = [`# Diagram changes: ${from} → ${to}`, ''];
|
|
198
|
+
const shown = diffs.filter((d) => d.status !== 'unchanged');
|
|
199
|
+
if (shown.length === 0)
|
|
200
|
+
out.push('No diagram changed.', '');
|
|
201
|
+
for (const d of shown) {
|
|
202
|
+
out.push(`## ${d.name}`, '');
|
|
203
|
+
if (d.status === 'error') {
|
|
204
|
+
out.push(`Not compared: ${d.error}`, '');
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
const f = files.get(d.name);
|
|
208
|
+
const cell = (rel, label) => rel === undefined ? '—' : f?.png === true ? `})` : `[${label}](${rel}.html)`;
|
|
209
|
+
out.push(`| Before (${from}) | After (${to}) |`, '| --- | --- |', `| ${cell(f?.before, 'before')} | ${cell(f?.after, 'after')} |`, '');
|
|
210
|
+
for (const l of describeDiff(d))
|
|
211
|
+
out.push(`- \`${l[0]}\` ${l.slice(2)}`);
|
|
212
|
+
out.push('');
|
|
213
|
+
}
|
|
214
|
+
return out.join('\n');
|
|
215
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
export interface CheckedOutRef {
|
|
2
|
+
/** the `.diagrams` directory as it was at the ref (it may not exist: the
|
|
3
|
+
* repo had no diagrams then) */
|
|
4
|
+
diagramsDir: string;
|
|
5
|
+
cleanup: () => Promise<void>;
|
|
6
|
+
}
|
|
7
|
+
/** `ref` resolved to a commit, or a readable error for a typo'd tag. */
|
|
8
|
+
export declare function verifyRef(ref: string, cwd: string): Promise<string>;
|
|
9
|
+
/**
|
|
10
|
+
* The tracked `.diagrams/` tree at `ref`, extracted into a temp directory —
|
|
11
|
+
* sources, layout sidecars, assets and the include snapshots, which is all a
|
|
12
|
+
* compile reads. `git archive` rather than a worktree: no checkout of the rest
|
|
13
|
+
* of the repo, and nothing left registered in `.git` if the run dies.
|
|
14
|
+
*
|
|
15
|
+
* `diagramsDir` is relative to `cwd`, which may sit below the repository root.
|
|
16
|
+
*/
|
|
17
|
+
export declare function checkoutDiagrams(ref: string, cwd: string, diagramsDir?: string): Promise<CheckedOutRef>;
|
package/dist/git-ref.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { mkdtemp, rm } from 'node:fs/promises';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { promisify } from 'node:util';
|
|
6
|
+
const run = promisify(execFile);
|
|
7
|
+
/** `ref` resolved to a commit, or a readable error for a typo'd tag. */
|
|
8
|
+
export async function verifyRef(ref, cwd) {
|
|
9
|
+
try {
|
|
10
|
+
const { stdout } = await run('git', ['rev-parse', '--verify', '--quiet', `${ref}^{commit}`], { cwd });
|
|
11
|
+
return stdout.trim();
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
throw new Error(`'${ref}' is not a commit, tag or branch in this repository`);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* The tracked `.diagrams/` tree at `ref`, extracted into a temp directory —
|
|
19
|
+
* sources, layout sidecars, assets and the include snapshots, which is all a
|
|
20
|
+
* compile reads. `git archive` rather than a worktree: no checkout of the rest
|
|
21
|
+
* of the repo, and nothing left registered in `.git` if the run dies.
|
|
22
|
+
*
|
|
23
|
+
* `diagramsDir` is relative to `cwd`, which may sit below the repository root.
|
|
24
|
+
*/
|
|
25
|
+
export async function checkoutDiagrams(ref, cwd, diagramsDir = '.diagrams') {
|
|
26
|
+
const commit = await verifyRef(ref, cwd);
|
|
27
|
+
// Every git call below runs at the top level with a top-level path: from a
|
|
28
|
+
// subdirectory, ls-tree and archive would read their paths relative to it.
|
|
29
|
+
const { stdout: top } = await run('git', ['rev-parse', '--show-toplevel'], { cwd });
|
|
30
|
+
const { stdout: prefix } = await run('git', ['rev-parse', '--show-prefix'], { cwd });
|
|
31
|
+
const repoPath = path.posix.normalize(path.posix.join(prefix.trim(), diagramsDir.split(path.sep).join('/')));
|
|
32
|
+
if (repoPath.startsWith('..'))
|
|
33
|
+
throw new Error(`${diagramsDir} is outside the repository`);
|
|
34
|
+
const root = await mkdtemp(path.join(tmpdir(), 'diagc-diff-'));
|
|
35
|
+
const cleanup = () => rm(root, { recursive: true, force: true });
|
|
36
|
+
const { stdout: listed } = await run('git', ['ls-tree', '--name-only', commit, '--', repoPath], { cwd: top.trim() });
|
|
37
|
+
if (listed.trim() !== '') {
|
|
38
|
+
try {
|
|
39
|
+
await pipeArchive(commit, repoPath, top.trim(), root);
|
|
40
|
+
}
|
|
41
|
+
catch (e) {
|
|
42
|
+
await cleanup();
|
|
43
|
+
throw e;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return { diagramsDir: path.join(root, ...repoPath.split('/')), cleanup };
|
|
47
|
+
}
|
|
48
|
+
/** `git archive <commit> -- <path> | tar -x -C <into>`, without a shell. */
|
|
49
|
+
function pipeArchive(commit, repoPath, cwd, into) {
|
|
50
|
+
return new Promise((resolve, reject) => {
|
|
51
|
+
const git = spawn('git', ['archive', '--format=tar', commit, '--', repoPath], { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
52
|
+
const tar = spawn('tar', ['-x', '-C', into], { stdio: ['pipe', 'ignore', 'pipe'] });
|
|
53
|
+
let err = '';
|
|
54
|
+
git.stderr.on('data', (d) => (err += d.toString()));
|
|
55
|
+
tar.stderr.on('data', (d) => (err += d.toString()));
|
|
56
|
+
git.stdout.pipe(tar.stdin);
|
|
57
|
+
let pending = 2;
|
|
58
|
+
let failed = false;
|
|
59
|
+
const done = (who) => (code) => {
|
|
60
|
+
if (code !== 0 && !failed) {
|
|
61
|
+
failed = true;
|
|
62
|
+
reject(new Error(`${who} failed extracting ${repoPath} at ${commit.slice(0, 12)}: ${err.trim()}`));
|
|
63
|
+
}
|
|
64
|
+
if (--pending === 0 && !failed)
|
|
65
|
+
resolve();
|
|
66
|
+
};
|
|
67
|
+
git.on('error', reject);
|
|
68
|
+
tar.on('error', reject);
|
|
69
|
+
git.on('close', done('git archive'));
|
|
70
|
+
tar.on('close', done('tar'));
|
|
71
|
+
});
|
|
72
|
+
}
|