@diagc/cli 1.1.5 → 1.1.7

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 (81) hide show
  1. package/dist/api/assets.d.ts +8 -0
  2. package/dist/api/assets.js +54 -0
  3. package/dist/api/diagrams.d.ts +27 -0
  4. package/dist/api/diagrams.js +269 -0
  5. package/dist/api/files.d.ts +7 -0
  6. package/dist/api/files.js +30 -0
  7. package/dist/api/handlers.d.ts +7 -62
  8. package/dist/api/handlers.js +10 -470
  9. package/dist/api/library.d.ts +5 -0
  10. package/dist/api/library.js +88 -0
  11. package/dist/api/result.d.ts +8 -0
  12. package/dist/api/result.js +5 -0
  13. package/dist/api/sidecars.d.ts +13 -0
  14. package/dist/api/sidecars.js +78 -0
  15. package/dist/cli/command.d.ts +26 -0
  16. package/dist/cli/command.js +1 -0
  17. package/dist/cli/io.d.ts +13 -0
  18. package/dist/cli/io.js +7 -0
  19. package/dist/cli/parse.d.ts +51 -0
  20. package/dist/cli/parse.js +109 -0
  21. package/dist/cli/run.d.ts +10 -0
  22. package/dist/cli/run.js +67 -0
  23. package/dist/cli.d.ts +1 -52
  24. package/dist/cli.js +13 -474
  25. package/dist/commands/compile.d.ts +3 -0
  26. package/dist/commands/compile.js +38 -0
  27. package/dist/commands/diff.d.ts +10 -0
  28. package/dist/commands/diff.js +96 -0
  29. package/dist/commands/eject.d.ts +3 -0
  30. package/dist/commands/eject.js +32 -0
  31. package/dist/commands/guide.d.ts +3 -0
  32. package/dist/commands/guide.js +13 -0
  33. package/dist/commands/init.d.ts +3 -0
  34. package/dist/commands/init.js +23 -0
  35. package/dist/commands/lint.d.ts +3 -0
  36. package/dist/commands/lint.js +27 -0
  37. package/dist/commands/publish.d.ts +11 -0
  38. package/dist/commands/publish.js +83 -0
  39. package/dist/commands/shared.d.ts +19 -0
  40. package/dist/commands/shared.js +34 -0
  41. package/dist/commands/studio.d.ts +3 -0
  42. package/dist/commands/studio.js +14 -0
  43. package/dist/commands/watch.d.ts +8 -0
  44. package/dist/commands/watch.js +45 -0
  45. package/dist/compile.d.ts +4 -1
  46. package/dist/compile.js +8 -13
  47. package/dist/diff/compare.d.ts +36 -0
  48. package/dist/diff/compare.js +36 -0
  49. package/dist/diff/describe.d.ts +8 -0
  50. package/dist/diff/describe.js +70 -0
  51. package/dist/diff/index.d.ts +4 -0
  52. package/dist/diff/index.js +6 -0
  53. package/dist/diff/load.d.ts +22 -0
  54. package/dist/diff/load.js +62 -0
  55. package/dist/diff/overview.d.ts +17 -0
  56. package/dist/diff/overview.js +86 -0
  57. package/dist/diff/pages.d.ts +27 -0
  58. package/dist/diff/pages.js +55 -0
  59. package/dist/diff/summary.d.ts +18 -0
  60. package/dist/diff/summary.js +26 -0
  61. package/dist/eject.js +2 -6
  62. package/dist/git-ref.js +21 -3
  63. package/dist/glob.d.ts +5 -0
  64. package/dist/glob.js +7 -0
  65. package/dist/init.d.ts +0 -3
  66. package/dist/init.js +14 -15
  67. package/dist/names.d.ts +3 -0
  68. package/dist/names.js +8 -0
  69. package/dist/paths.d.ts +29 -0
  70. package/dist/paths.js +25 -0
  71. package/dist/publish/discover.js +2 -1
  72. package/dist/publish/publish.d.ts +6 -4
  73. package/dist/publish/publish.js +11 -7
  74. package/dist/snapshots.d.ts +11 -0
  75. package/dist/snapshots.js +20 -3
  76. package/dist/studio.js +8 -8
  77. package/package.json +2 -2
  78. package/dist/command-args.d.ts +0 -9
  79. package/dist/command-args.js +0 -56
  80. package/dist/diff.d.ts +0 -61
  81. package/dist/diff.js +0 -244
package/dist/cli.js CHANGED
@@ -19,26 +19,8 @@
19
19
  *
20
20
  * SPDX-License-Identifier: AGPL-3.0-only
21
21
  */
22
- import { existsSync, statSync } from 'node:fs';
23
- import path from 'node:path';
24
- import { fileURLToPath } from 'node:url';
25
- import fg from 'fast-glob';
26
- import { errMessage } from '@diagc/core/internal';
27
- import { compileFile } from './compile.js';
28
- import { compareDiagramSets, formatDiffSummary, loadDiagramSet, writeDiffPages } from './diff.js';
29
- import { checkoutDiagrams } from './git-ref.js';
30
- import { ejectDiagram } from './eject.js';
31
- import { formatLintReport, lintFile } from './lint.js';
32
- import { runGuide } from './guide.js';
33
- import { cliVersion, findHome, homePaths } from './home.js';
34
- import { diagramName, runInit } from './init.js';
35
- import { resolveInclude } from './includes.js';
36
- import { snapshotSession } from './snapshots.js';
37
- import { formatCompileEvent, startWatch } from './watch.js';
38
- import { galleryLink } from './publish/gallery.js';
39
- import { publishDiagrams } from './publish/publish.js';
40
- import { runStudio } from './studio.js';
41
- import { ArgNotTakenError, checkCommandArgs } from './command-args.js';
22
+ import { processIo } from './cli/io.js';
23
+ import { run } from './cli/run.js';
42
24
  const USAGE = `Usage: diagc <init|compile|lint|watch|publish|studio|eject|diff|guide> [files...] [--out dir]
43
25
 
44
26
  Commands:
@@ -71,460 +53,17 @@ Options:
71
53
  the skill into .claude/skills/diagc/ where Claude Code is in use
72
54
  --help, -h Show this help and exit
73
55
  `;
74
- /** Parse argv into command + flags. Unknown flags (anything `--…` that is not
75
- * recognized) are an error rather than being silently treated as a file path,
76
- * so a typo surfaces loudly instead of quietly skewing the file set. */
77
- export function parseArgs(argv) {
78
- let command = 'compile';
79
- const files = [];
80
- let out = '.diagrams/.artifacts';
81
- let outGiven = false;
82
- let images = true;
83
- let updateIncludes = false;
84
- let json = false;
85
- let link;
86
- let imageUrl;
87
- let labels;
88
- let type;
89
- let agents = false;
90
- let commandSeen = false;
91
- for (let i = 0; i < argv.length; i++) {
92
- const arg = argv[i];
93
- if (arg === '--out') {
94
- // No fallback to the default: a trailing --out would quietly write somewhere the
95
- // user did not ask for, and a missing value would swallow the next flag as the dir.
96
- const value = argv[i + 1];
97
- if (value === undefined || value.startsWith('--'))
98
- throw new BadFlagValueError('--out', 'needs a directory, e.g. --out build/artifacts');
99
- out = value;
100
- outGiven = true;
101
- i++;
102
- continue;
103
- }
104
- if (arg === '--no-images') {
105
- images = false;
106
- continue;
107
- }
108
- if (arg === '--update-includes') {
109
- updateIncludes = true;
110
- continue;
111
- }
112
- if (arg === '--json') {
113
- json = true;
114
- continue;
115
- }
116
- if (arg === '--type') {
117
- // No fallback: a missing value would otherwise swallow the next flag as the type.
118
- const value = argv[i + 1];
119
- if (value === undefined || value.startsWith('--'))
120
- throw new BadFlagValueError('--type', "needs a diagram type, e.g. --type c4 ('diagc guide' lists them)");
121
- type = value;
122
- i++;
123
- continue;
124
- }
125
- if (arg === '--agents') {
126
- agents = true;
127
- continue;
128
- }
129
- if (arg === '--image-url') {
130
- const value = argv[++i] ?? '';
131
- if (!value.includes('{path}'))
132
- throw new BadFlagValueError('--image-url', 'needs a {path} placeholder, e.g. https://host/pr-1/{path}');
133
- imageUrl = value;
134
- continue;
135
- }
136
- if (arg === '--labels') {
137
- const parts = (argv[++i] ?? '').split(',');
138
- if (parts.length !== 2 || parts.some((p) => p.trim() === ''))
139
- throw new BadFlagValueError('--labels', 'takes two names, before and after: --labels main,#12');
140
- labels = [parts[0].trim(), parts[1].trim()];
141
- continue;
142
- }
143
- if (arg === '--link') {
144
- // No fallback for a missing value: there is no default address, and the URL
145
- // check is also what stops the next flag being swallowed as one.
146
- const value = argv[++i] ?? '';
147
- try {
148
- galleryLink(value);
149
- }
150
- catch (e) {
151
- throw new BadFlagValueError('--link', errMessage(e));
152
- }
153
- link = value;
154
- continue;
155
- }
156
- if (arg === '--help' || arg === '-h')
157
- throw new HelpRequested();
158
- if (arg.startsWith('--'))
159
- throw new UnknownFlagError(arg);
160
- // The first non-flag argument names the command; anything after it is a
161
- // file path (flags may appear before or after the command).
162
- if (!commandSeen) {
163
- command = arg;
164
- commandSeen = true;
165
- }
166
- else {
167
- files.push(arg);
168
- }
169
- }
170
- return {
171
- command,
172
- files,
173
- out,
174
- outGiven,
175
- images,
176
- updateIncludes,
177
- json,
178
- agents,
179
- ...(type !== undefined ? { type } : {}),
180
- ...(link !== undefined ? { link } : {}),
181
- ...(imageUrl !== undefined ? { imageUrl } : {}),
182
- ...(labels !== undefined ? { labels } : {}),
183
- };
184
- }
185
- /** Thrown by {@link parseArgs} for `--help`/`-h`; `main` prints usage and exits 0. */
186
- export class HelpRequested extends Error {
187
- constructor() {
188
- super('help requested');
189
- this.name = 'HelpRequested';
190
- }
191
- }
192
- /** Thrown by {@link parseArgs} for an unrecognized flag; `main` prints the
193
- * offending flag plus usage and exits 1. */
194
- export class UnknownFlagError extends Error {
195
- constructor(flag) {
196
- super(`Unknown flag '${flag}'`);
197
- this.name = 'UnknownFlagError';
198
- }
199
- }
200
- /** Thrown by {@link parseArgs} for a flag whose value is missing or unusable; `main`
201
- * reports it the same way as an unknown flag. */
202
- export class BadFlagValueError extends Error {
203
- constructor(flag, why) {
204
- super(`${flag}: ${why}`);
205
- this.name = 'BadFlagValueError';
206
- }
207
- }
208
- const SOURCES = '.diagrams/src/**/*.diagram.{ts,json}';
209
- /** The one message a repository with no diagrams gets, on stderr: `lint --json`'s
210
- * stdout stays an array and the exit codes hold, so CI without diagrams passes. */
211
- function warnNoSources(dir = '.diagrams/src') {
212
- console.error(`No diagrams under ${dir} — run 'diagc init' to create one.`);
213
- }
214
- /** Where `publish` compiles to and builds pages from. One object for both steps, so
215
- * the pages are always made from the artifacts this run just wrote. `--out` moves the
216
- * artifacts only: the pages and PNGs stay where `.gitignore`, the docs and the READMEs
217
- * that embed them expect to find them. */
218
- export function publishDirs(args) {
219
- const srcDir = '.diagrams/src';
220
- return {
221
- srcDir,
222
- artifactsDir: args.out,
223
- htmlDir: '.diagrams/html',
224
- staticDir: '.diagrams/static',
225
- assetsDir: path.join(srcDir, 'assets'),
226
- };
56
+ /** End the process once stdout and stderr have taken everything written to them:
57
+ * `process.exit` straight after a write drops what a pipe has not accepted yet. A
58
+ * zero-length write's callback runs after everything queued before it. It ends with
59
+ * `process.exit`, not `exitCode`, so an open handle (a keep-alive socket from a remote
60
+ * include, a Chrome process) cannot keep the CLI running. */
61
+ async function exit(code) {
62
+ await Promise.all([process.stdout, process.stderr].map((s) => new Promise((done) => s.write('', done))));
63
+ process.exit(code);
227
64
  }
65
+ /** The binary: argv through the process's own streams, then exit with the code. */
228
66
  async function main() {
229
- let args;
230
- try {
231
- args = parseArgs(process.argv.slice(2));
232
- checkCommandArgs(args);
233
- }
234
- catch (e) {
235
- if (e instanceof HelpRequested) {
236
- console.log(USAGE);
237
- process.exit(0);
238
- }
239
- if (e instanceof UnknownFlagError || e instanceof BadFlagValueError || e instanceof ArgNotTakenError) {
240
- console.error(`diagc: ${e.message}\n`);
241
- console.error(USAGE);
242
- process.exit(1);
243
- }
244
- throw e;
245
- }
246
- const home = homePaths(findHome(fileURLToPath(import.meta.url)));
247
- // One session per CLI invocation, shared across every compile+publish in this
248
- // run: the in-memory lock + touched set must span the whole run for prune()
249
- // to see everything a full-tree compile actually resolved. `watch` builds its
250
- // own separate always-locked session below instead of sharing this one.
251
- const snap = snapshotSession(resolveInclude, '.diagrams', args.updateIncludes ? 'update' : 'locked');
252
- if (args.command === 'compile') {
253
- const files = args.files.length > 0 ? args.files : await fg(SOURCES);
254
- if (args.files.length === 0 && files.length === 0)
255
- warnNoSources();
256
- let failed = false;
257
- for (const file of files) {
258
- try {
259
- const artifact = await compileFile(file, args.out, {
260
- rootDir: '.diagrams/src',
261
- coreEntry: home.coreEntry,
262
- resolver: snap.resolver,
263
- });
264
- console.log(formatCompileEvent({ file, ok: true, artifact }));
265
- }
266
- catch (e) {
267
- failed = true;
268
- console.error(formatCompileEvent({ file, ok: false, error: errMessage(e) }));
269
- }
270
- }
271
- // A source that fails before include resolution (e.g. a pre-compose
272
- // validation error) never touches its remote URLs, so pruning here would
273
- // drop their still-valid lock entries and vendored files right along with
274
- // the genuinely stale ones — skip the prune until every file compiles clean.
275
- if (args.updateIncludes && args.files.length === 0 && !failed)
276
- await snap.prune();
277
- process.exit(failed ? 1 : 0);
278
- }
279
- else if (args.command === 'lint') {
280
- const files = args.files.length > 0 ? args.files : await fg(SOURCES);
281
- if (args.files.length === 0 && files.length === 0)
282
- warnNoSources();
283
- const reports = [];
284
- for (const file of files) {
285
- reports.push(...(await lintFile(file, { rootDir: '.diagrams/src', coreEntry: home.coreEntry, resolver: snap.resolver })));
286
- }
287
- if (args.json)
288
- console.log(JSON.stringify(reports, null, 2));
289
- else
290
- for (const r of reports)
291
- console.log(formatLintReport(r));
292
- process.exit(reports.length > 0 ? 1 : 0);
293
- }
294
- else if (args.command === 'watch') {
295
- // Always locked, and --update-includes is refused here: watch is a long-running
296
- // live loop with no point at which "refetch and rewrite the lock" makes
297
- // sense, so it has its own session rather than the shared one (mirrors
298
- // studio.ts's own hardcoded 'locked' session).
299
- const dir = args.files[0] ?? '.diagrams/src';
300
- if (existsSync(dir) &&
301
- statSync(dir).isDirectory() &&
302
- (await fg('**/*.diagram.{ts,json}', { cwd: dir })).length === 0)
303
- warnNoSources(dir);
304
- const watchSnap = snapshotSession(resolveInclude, '.diagrams', 'locked');
305
- startWatch(dir, args.out, {
306
- coreEntry: home.coreEntry,
307
- resolver: watchSnap.resolver,
308
- onEvent: (e) => {
309
- // Success goes to stdout, failure to stderr, so the streams stay parsed
310
- // separately by anyone piping them.
311
- if (e.ok)
312
- console.log(formatCompileEvent(e));
313
- else
314
- console.error(formatCompileEvent(e));
315
- },
316
- });
317
- console.log(`Watching ${dir} for *.diagram.{ts,json} changes...`);
318
- }
319
- else if (args.command === 'publish') {
320
- if (!existsSync(home.viewerShell)) {
321
- // Only a checkout can be missing it; an installed package ships the shell,
322
- // so there the message would send the reader off to build a repo they
323
- // do not have.
324
- console.error(home.layout === 'monorepo'
325
- ? 'viewer shell not built — run `pnpm --filter @diagc/viewer build` in the monorepo.'
326
- : `viewer shell missing from this install (${home.viewerShell}) — reinstall diagc.`);
327
- process.exit(1);
328
- }
329
- const dirs = publishDirs(args);
330
- // Compile first so artifacts reflect current sources (TS + include expansion).
331
- const sources = await fg('**/*.diagram.{ts,json}', { cwd: dirs.srcDir, absolute: true });
332
- if (sources.length === 0)
333
- warnNoSources(dirs.srcDir);
334
- let failed = false;
335
- for (const f of sources) {
336
- try {
337
- await compileFile(f, dirs.artifactsDir, {
338
- rootDir: dirs.srcDir,
339
- coreEntry: home.coreEntry,
340
- resolver: snap.resolver,
341
- });
342
- }
343
- catch (e) {
344
- failed = true;
345
- console.error(`✗ ${f}\n${errMessage(e)}`);
346
- }
347
- }
348
- // publish's glob above ignores args.files (that only scopes which rendered
349
- // pages come out below), so an update run here is always full-tree; like
350
- // compile's, its prune waits until every source compiles.
351
- if (args.updateIncludes && !failed)
352
- await snap.prune();
353
- let images = args.images;
354
- let renderPng;
355
- if (args.images) {
356
- const snapshot = await import('./publish/snapshot.js');
357
- if (snapshot.findChrome() === undefined) {
358
- console.log('No Chrome found — writing HTML only; install Chrome / set CHROME_PATH, or use --no-images.');
359
- images = false;
360
- }
361
- else {
362
- renderPng = snapshot.renderPng;
363
- }
364
- }
365
- const res = await publishDiagrams({
366
- ...dirs,
367
- shellPath: home.viewerShell,
368
- libraryDir: home.libraryDir,
369
- images,
370
- names: args.files,
371
- ...(renderPng !== undefined ? { renderPng } : {}),
372
- ...(args.link !== undefined ? { link: args.link } : {}),
373
- });
374
- console.log(`✓ ${res.pages.length} page(s) -> ${dirs.htmlDir}`);
375
- if (res.images.length > 0)
376
- console.log(`✓ ${res.images.length} image(s) -> ${dirs.staticDir}`);
377
- console.log(`✓ gallery -> ${res.gallery}`);
378
- process.exit(0);
379
- }
380
- else if (args.command === 'studio') {
381
- // Studio's own compile-watch loop always resolves includes locked (see
382
- // studio.ts) — same reasoning as watch above.
383
- await runStudio(home, process.cwd());
384
- return;
385
- }
386
- else if (args.command === 'eject') {
387
- // ejectDiagram's post-swap recompile always resolves includes locked (see
388
- // eject.ts) — same reasoning as watch above.
389
- const name = args.files[0] === undefined ? undefined : diagramName(args.files[0]);
390
- if (name === undefined || name === '') {
391
- console.error('diagc: eject needs a diagram name.');
392
- console.error(USAGE);
393
- process.exit(1);
394
- }
395
- try {
396
- const res = await ejectDiagram('.diagrams/src', args.out, name, { coreEntry: home.coreEntry });
397
- console.log(`✓ ${res.tsPath}`);
398
- process.exit(0);
399
- }
400
- catch (e) {
401
- console.error(errMessage(e));
402
- process.exit(1);
403
- }
404
- }
405
- else if (args.command === 'diff') {
406
- process.exit(await runDiff(args, home));
407
- }
408
- else if (args.command === 'guide') {
409
- // exitCode and a return, not process.exit: the guide is tens of kilobytes and
410
- // is read through a pipe by an agent. Exiting while part of it is still
411
- // queued would hand over a page that stops mid-sentence.
412
- process.exitCode = runGuide(args.files, {
413
- guideDir: home.guideDir,
414
- startersDir: home.startersDir,
415
- version: cliVersion(home.root),
416
- });
417
- return;
418
- }
419
- else if (args.command === 'init') {
420
- if (args.files.length > 1) {
421
- console.error(`diagc: init takes one name, got ${args.files.length} — e.g. diagc init shop --type c4`);
422
- process.exit(1);
423
- }
424
- process.exitCode = await runInit({
425
- cwd: process.cwd(),
426
- ...(args.files[0] !== undefined ? { name: args.files[0] } : {}),
427
- ...(args.type !== undefined ? { type: args.type } : {}),
428
- agents: args.agents,
429
- startersDir: home.startersDir,
430
- skillFile: home.skillFile,
431
- version: cliVersion(home.root),
432
- coreEntry: home.coreEntry,
433
- resolver: snap.resolver,
434
- });
435
- return;
436
- }
437
- else {
438
- console.error(`diagc: Unknown command '${args.command}'.`);
439
- console.error(USAGE);
440
- process.exit(1);
441
- }
442
- }
443
- /** `A..B` or `A` (against the working tree). */
444
- export function parseRange(range) {
445
- const at = range.indexOf('..');
446
- if (at === -1)
447
- return { from: range };
448
- const from = range.slice(0, at);
449
- const to = range.slice(at + 2);
450
- if (from === '' || to === '' || to.startsWith('.'))
451
- throw new Error(`'${range}' is not a range: write <from>..<to>, or one ref to compare with the working tree`);
452
- return { from, to };
453
- }
454
- /** A ref as a directory name: `v1.0..feature/x` -> `v1.0..feature-x`. */
455
- export function diffOutDir(from, to) {
456
- const safe = (s) => s.replace(/[^A-Za-z0-9._-]+/g, '-');
457
- return path.join('.diagrams', 'diff', `${safe(from)}..${to !== undefined ? safe(to) : 'working-tree'}`);
458
- }
459
- async function runDiff(args, home) {
460
- const range = args.files[0];
461
- if (range === undefined) {
462
- console.error('diagc: diff needs a git ref (diff v1.0) or a range (diff v1.0..v2.0).');
463
- console.error(USAGE);
464
- return 1;
465
- }
466
- const checkouts = [];
467
- try {
468
- const { from, to } = parseRange(range);
469
- const before = await checkoutDiagrams(from, process.cwd());
470
- checkouts.push(before);
471
- let afterDir = '.diagrams';
472
- if (to !== undefined) {
473
- const after = await checkoutDiagrams(to, process.cwd());
474
- checkouts.push(after);
475
- afterDir = after.diagramsDir;
476
- }
477
- const fromLabel = args.labels?.[0] ?? from;
478
- const toLabel = args.labels?.[1] ?? to ?? 'working tree';
479
- const beforeSet = await loadDiagramSet(fromLabel, before.diagramsDir, home.coreEntry);
480
- const afterSet = await loadDiagramSet(toLabel, afterDir, home.coreEntry);
481
- const diffs = compareDiagramSets(beforeSet, afterSet, args.files.slice(1));
482
- if (args.json) {
483
- console.log(JSON.stringify({ from: fromLabel, to: toLabel, diagrams: diffs.map(({ before: _b, after: _a, ...rest }) => rest) }, null, 2));
484
- }
485
- else {
486
- console.log(formatDiffSummary(diffs, fromLabel, toLabel));
487
- }
488
- if (!diffs.some((d) => d.status === 'added' || d.status === 'removed' || d.status === 'changed'))
489
- return 0;
490
- if (!existsSync(home.viewerShell)) {
491
- console.error('viewer shell not available — writing the summary only (see `diagc publish` for how to build it).');
492
- return 0;
493
- }
494
- let renderPng;
495
- if (args.images) {
496
- const snapshot = await import('./publish/snapshot.js');
497
- if (snapshot.findChrome() === undefined)
498
- console.error('No Chrome found — writing HTML only; install Chrome / set CHROME_PATH, or use --no-images.');
499
- else
500
- renderPng = snapshot.renderPng;
501
- }
502
- const outDir = args.outGiven ? args.out : diffOutDir(from, to);
503
- const res = await writeDiffPages(diffs, {
504
- outDir,
505
- shellPath: home.viewerShell,
506
- libraryDir: home.libraryDir,
507
- before: beforeSet,
508
- after: afterSet,
509
- ...(renderPng !== undefined ? { renderPng } : {}),
510
- ...(args.imageUrl !== undefined ? { imageUrl: args.imageUrl } : {}),
511
- });
512
- // stderr, so `--json` output stays parseable on stdout
513
- console.error(`✓ ${res.pages.length} page(s)${res.images.length > 0 ? `, ${res.images.length} image(s)` : ''} -> ${outDir}`);
514
- console.error(`✓ side by side -> ${res.index}`);
515
- console.error(`✓ for an ADR -> ${res.summary}`);
516
- return 0;
517
- }
518
- catch (e) {
519
- console.error(`diagc: ${errMessage(e)}`);
520
- return 1;
521
- }
522
- finally {
523
- for (const c of checkouts)
524
- await c.cleanup();
525
- }
67
+ return exit(await run(process.argv.slice(2), processIo, USAGE));
526
68
  }
527
- main().catch((e) => {
528
- console.error(errMessage(e));
529
- process.exit(1);
530
- });
69
+ void main();
@@ -0,0 +1,3 @@
1
+ import type { Command } from '../cli/command.js';
2
+ /** `diagc compile [files...]`: the files named, or every source, into artifacts. */
3
+ export declare const compile: Command<'--out' | '--update-includes'>;
@@ -0,0 +1,38 @@
1
+ import { errMessage } from '@diagc/core/internal';
2
+ import { compileFile } from '../compile.js';
3
+ import { globSorted } from '../glob.js';
4
+ import { RELATIVE_PATHS } from '../paths.js';
5
+ import { formatCompileEvent } from '../watch.js';
6
+ import { SOURCES, warnNoSources } from './shared.js';
7
+ /** `diagc compile [files...]`: the files named, or every source, into artifacts. */
8
+ export const compile = {
9
+ flags: ['--out', '--update-includes'],
10
+ async run({ positionals, flags }, { io, home, snapshots }) {
11
+ const files = positionals.length > 0 ? positionals : await globSorted(SOURCES);
12
+ if (positionals.length === 0 && files.length === 0)
13
+ warnNoSources(io);
14
+ let failed = false;
15
+ for (const file of files) {
16
+ try {
17
+ const artifact = await compileFile(file, flags['--out'] ?? RELATIVE_PATHS.artifactsDir, {
18
+ rootDir: RELATIVE_PATHS.srcDir,
19
+ coreEntry: home.coreEntry,
20
+ resolver: snapshots.resolver,
21
+ warn: io.err,
22
+ });
23
+ io.out(formatCompileEvent({ file, ok: true, artifact }));
24
+ }
25
+ catch (e) {
26
+ failed = true;
27
+ io.err(formatCompileEvent({ file, ok: false, error: errMessage(e) }));
28
+ }
29
+ }
30
+ // A source that fails before include resolution (e.g. a pre-compose
31
+ // validation error) never touches its remote URLs, so pruning here would
32
+ // drop their still-valid lock entries and vendored files right along with
33
+ // the genuinely stale ones — skip the prune until every file compiles clean.
34
+ if (flags['--update-includes'] === true && positionals.length === 0 && !failed)
35
+ await snapshots.prune();
36
+ return failed ? 1 : 0;
37
+ },
38
+ };
@@ -0,0 +1,10 @@
1
+ import type { Command } from '../cli/command.js';
2
+ /** `A..B` or `A` (against the working tree). */
3
+ export declare function parseRange(range: string): {
4
+ from: string;
5
+ to?: string;
6
+ };
7
+ /** A ref as a directory name: `v1.0..feature/x` -> `v1.0..feature-x`. */
8
+ export declare function diffOutDir(from: string, to: string | undefined): string;
9
+ /** `diagc diff <from>[..<to>] [names...]`: what changed, and the pages that show it. */
10
+ export declare const diff: Command<'--out' | '--no-images' | '--json' | '--labels' | '--image-url'>;
@@ -0,0 +1,96 @@
1
+ import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { errMessage } from '@diagc/core/internal';
4
+ import { compareDiagramSets, formatDiffJson, formatDiffSummary, loadDiagramSet, writeDiffPages, } from '../diff/index.js';
5
+ import { checkoutDiagrams } from '../git-ref.js';
6
+ import { RELATIVE_PATHS } from '../paths.js';
7
+ import { diagramNames, pngRenderer } from './shared.js';
8
+ /** `A..B` or `A` (against the working tree). */
9
+ export function parseRange(range) {
10
+ const at = range.indexOf('..');
11
+ if (at === -1)
12
+ return { from: range };
13
+ const from = range.slice(0, at);
14
+ const to = range.slice(at + 2);
15
+ if (from === '' || to === '' || to.startsWith('.'))
16
+ throw new Error(`'${range}' is not a range: write <from>..<to>, or one ref to compare with the working tree`);
17
+ return { from, to };
18
+ }
19
+ /** A ref as a directory name: `v1.0..feature/x` -> `v1.0..feature-x`. */
20
+ export function diffOutDir(from, to) {
21
+ const safe = (s) => s.replace(/[^A-Za-z0-9._-]+/g, '-');
22
+ return path.join(RELATIVE_PATHS.diffDir, `${safe(from)}..${to !== undefined ? safe(to) : 'working-tree'}`);
23
+ }
24
+ /** Each sidecar diff left out of its pictures, on stderr so `--json` stays parseable. */
25
+ function warnLeftOut(io, ...sets) {
26
+ for (const set of sets)
27
+ for (const w of set.warnings)
28
+ io.err(w);
29
+ }
30
+ /** `diagc diff <from>[..<to>] [names...]`: what changed, and the pages that show it. */
31
+ export const diff = {
32
+ flags: ['--out', '--no-images', '--json', '--labels', '--image-url'],
33
+ async run({ positionals, flags }, { io, usage, home }) {
34
+ const range = positionals[0];
35
+ if (range === undefined) {
36
+ io.err('diagc: diff needs a git ref (diff v1.0) or a range (diff v1.0..v2.0).');
37
+ io.err(usage);
38
+ return 1;
39
+ }
40
+ const checkouts = [];
41
+ try {
42
+ const { from, to } = parseRange(range);
43
+ const before = await checkoutDiagrams(from, process.cwd());
44
+ checkouts.push(before);
45
+ let afterDir = RELATIVE_PATHS.diagramsDir;
46
+ if (to !== undefined) {
47
+ const after = await checkoutDiagrams(to, process.cwd());
48
+ checkouts.push(after);
49
+ afterDir = after.diagramsDir;
50
+ }
51
+ const fromLabel = flags['--labels']?.[0] ?? from;
52
+ const toLabel = flags['--labels']?.[1] ?? to ?? 'working tree';
53
+ const beforeSet = await loadDiagramSet(fromLabel, before.diagramsDir, home.coreEntry);
54
+ const afterSet = await loadDiagramSet(toLabel, afterDir, home.coreEntry);
55
+ warnLeftOut(io, beforeSet, afterSet);
56
+ const known = new Set([beforeSet, afterSet].flatMap((set) => [...set.versions.keys(), ...set.errors.keys()]));
57
+ const names = diagramNames(io, positionals.slice(1), known);
58
+ if (names === undefined)
59
+ return 1;
60
+ const diffs = compareDiagramSets(beforeSet, afterSet, names);
61
+ io.out(flags['--json'] === true
62
+ ? formatDiffJson(diffs, fromLabel, toLabel)
63
+ : formatDiffSummary(diffs, fromLabel, toLabel));
64
+ if (!diffs.some((d) => d.status === 'added' || d.status === 'removed' || d.status === 'changed'))
65
+ return 0;
66
+ if (!existsSync(home.viewerShell)) {
67
+ io.err('viewer shell not available — writing the summary only (see `diagc publish` for how to build it).');
68
+ return 0;
69
+ }
70
+ const renderPng = await pngRenderer(io, flags['--no-images'] !== true);
71
+ const outDir = flags['--out'] ?? diffOutDir(from, to);
72
+ const res = await writeDiffPages(diffs, {
73
+ outDir,
74
+ shellPath: home.viewerShell,
75
+ libraryDir: home.libraryDir,
76
+ before: beforeSet,
77
+ after: afterSet,
78
+ ...(renderPng !== undefined ? { renderPng } : {}),
79
+ ...(flags['--image-url'] !== undefined ? { imageUrl: flags['--image-url'] } : {}),
80
+ });
81
+ // stderr, so `--json` output stays parseable on stdout
82
+ io.err(`✓ ${res.pages.length} page(s)${res.images.length > 0 ? `, ${res.images.length} image(s)` : ''} -> ${outDir}`);
83
+ io.err(`✓ side by side -> ${res.index}`);
84
+ io.err(`✓ for an ADR -> ${res.summary}`);
85
+ return 0;
86
+ }
87
+ catch (e) {
88
+ io.err(`diagc: ${errMessage(e)}`);
89
+ return 1;
90
+ }
91
+ finally {
92
+ for (const c of checkouts)
93
+ await c.cleanup();
94
+ }
95
+ },
96
+ };
@@ -0,0 +1,3 @@
1
+ import type { Command } from '../cli/command.js';
2
+ /** `diagc eject <name>`: a JSON diagram as a generated TypeScript source. */
3
+ export declare const eject: Command<'--out'>;