@diagc/cli 1.4.0 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/assets/guide/index.md +1 -1
  2. package/assets/skill/SKILL.md +1 -1
  3. package/assets/studio/assets/{index-B4EbTBLO.js → index-DRsUukzt.js} +48 -46
  4. package/assets/studio/index.html +1 -1
  5. package/dist/api/diagrams.d.ts +5 -0
  6. package/dist/api/diagrams.js +37 -24
  7. package/dist/api/dispatch.d.ts +3 -0
  8. package/dist/api/handlers.d.ts +1 -0
  9. package/dist/api/handlers.js +1 -0
  10. package/dist/api/pages.d.ts +21 -0
  11. package/dist/api/pages.js +50 -0
  12. package/dist/api/routes.d.ts +2 -0
  13. package/dist/api/routes.js +6 -0
  14. package/dist/cli/io.d.ts +5 -0
  15. package/dist/cli/io.js +4 -0
  16. package/dist/cli/parse.d.ts +7 -0
  17. package/dist/cli/parse.js +25 -0
  18. package/dist/cli/run.js +4 -0
  19. package/dist/cli.js +23 -1
  20. package/dist/commands/shared.d.ts +4 -0
  21. package/dist/commands/shared.js +13 -0
  22. package/dist/commands/show.d.ts +5 -0
  23. package/dist/commands/show.js +115 -0
  24. package/dist/commands/tui.d.ts +3 -0
  25. package/dist/commands/tui.js +36 -0
  26. package/dist/init.d.ts +1 -1
  27. package/dist/init.js +1 -1
  28. package/dist/publish/publish.d.ts +15 -1
  29. package/dist/publish/publish.js +22 -15
  30. package/dist/serve.d.ts +3 -0
  31. package/dist/serve.js +2 -2
  32. package/dist/studio.js +1 -0
  33. package/dist/text/accents.d.ts +9 -0
  34. package/dist/text/accents.js +83 -0
  35. package/dist/text/ansi.d.ts +28 -0
  36. package/dist/text/ansi.js +111 -0
  37. package/dist/text/braille.d.ts +28 -0
  38. package/dist/text/braille.js +58 -0
  39. package/dist/text/canvas.d.ts +65 -0
  40. package/dist/text/canvas.js +155 -0
  41. package/dist/text/content.d.ts +32 -0
  42. package/dist/text/content.js +90 -0
  43. package/dist/text/fish.d.ts +27 -0
  44. package/dist/text/fish.js +209 -0
  45. package/dist/text/folds.d.ts +14 -0
  46. package/dist/text/folds.js +45 -0
  47. package/dist/text/glyphs.d.ts +31 -0
  48. package/dist/text/glyphs.js +84 -0
  49. package/dist/text/layout.d.ts +61 -0
  50. package/dist/text/layout.js +334 -0
  51. package/dist/text/legend.d.ts +44 -0
  52. package/dist/text/legend.js +252 -0
  53. package/dist/text/paint.d.ts +25 -0
  54. package/dist/text/paint.js +208 -0
  55. package/dist/text/render.d.ts +11 -0
  56. package/dist/text/render.js +28 -0
  57. package/dist/text/scene.d.ts +40 -0
  58. package/dist/text/scene.js +50 -0
  59. package/dist/text/vocabulary.d.ts +37 -0
  60. package/dist/text/vocabulary.js +211 -0
  61. package/dist/text/width.d.ts +15 -0
  62. package/dist/text/width.js +181 -0
  63. package/dist/tui/actions.d.ts +10 -0
  64. package/dist/tui/actions.js +297 -0
  65. package/dist/tui/app.d.ts +31 -0
  66. package/dist/tui/app.js +389 -0
  67. package/dist/tui/details.d.ts +3 -0
  68. package/dist/tui/details.js +54 -0
  69. package/dist/tui/keys.d.ts +33 -0
  70. package/dist/tui/keys.js +113 -0
  71. package/dist/tui/kitty.d.ts +36 -0
  72. package/dist/tui/kitty.js +65 -0
  73. package/dist/tui/legend.d.ts +14 -0
  74. package/dist/tui/legend.js +18 -0
  75. package/dist/tui/nav.d.ts +25 -0
  76. package/dist/tui/nav.js +79 -0
  77. package/dist/tui/overview.d.ts +46 -0
  78. package/dist/tui/overview.js +115 -0
  79. package/dist/tui/pixels.d.ts +28 -0
  80. package/dist/tui/pixels.js +80 -0
  81. package/dist/tui/screen.d.ts +44 -0
  82. package/dist/tui/screen.js +335 -0
  83. package/dist/tui/state.d.ts +100 -0
  84. package/dist/tui/state.js +72 -0
  85. package/dist/tui/terminal.d.ts +21 -0
  86. package/dist/tui/terminal.js +53 -0
  87. package/dist/watch.d.ts +2 -0
  88. package/dist/watch.js +1 -0
  89. package/package.json +3 -2
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>diagc studio</title>
7
- <script type="module" crossorigin src="/assets/index-B4EbTBLO.js"></script>
7
+ <script type="module" crossorigin src="/assets/index-DRsUukzt.js"></script>
8
8
  <link rel="stylesheet" crossorigin href="/assets/index-DzVDK5uD.css">
9
9
  </head>
10
10
  <body>
@@ -12,6 +12,11 @@ export interface DiagramEntry {
12
12
  * `diagramsDir`, compiled TS artifacts from `artifactsDir`. A source shadows its
13
13
  * artifact so unsaved-compile staleness never shows. */
14
14
  export declare function listDiagramModels(diagramsDir: string, artifactsDir: string): Promise<HandlerResult>;
15
+ /** The diagram `name` as the studio's list shows it, or undefined when the list has
16
+ * no such name. Looking the name up in the listing, rather than checking its
17
+ * spelling, is what keeps it inside the two directories: a compiled diagram's name
18
+ * comes from its `.diagram.ts` file and need not pass `isSafeName`. */
19
+ export declare function diagramAsShown(diagramsDir: string, artifactsDir: string, name: string): Promise<DiagramEntry | undefined>;
15
20
  /** the JSON source (+ sibling layout and drawings) of a designer-owned diagram — the studio
16
21
  * reads these directly so it never depends on a compile watcher for its own files */
17
22
  export declare function readDiagram(diagramsDir: string, name: string): Promise<HandlerResult>;
@@ -16,32 +16,45 @@ export async function listDiagramModels(diagramsDir, artifactsDir) {
16
16
  const artifactNames = await walkDiagramJson(artifactsDir);
17
17
  const all = [...new Set([...sourceNames, ...artifactNames])].sort();
18
18
  const diagrams = [];
19
- for (const name of all) {
20
- const isSource = sourceNames.has(name);
21
- // Every read and save refuses a name isSafeName refuses, so such a source is shown but not offered for editing.
22
- const editable = isSource && isSafeName(name);
23
- const file = isSource
24
- ? path.join(diagramsDir, `${name}.diagram.json`)
25
- : path.join(artifactsDir, `${name}.diagram.json`);
26
- let model = null;
27
- const issues = [];
28
- if (isSource && !editable) {
29
- issues.push({
30
- message: `'${name}' is read-only here: the studio saves names of lowercase letters, digits, '-' and '/', none ending in /rename, /eject or /composed. Rename the file to edit it.`,
31
- });
32
- }
33
- try {
34
- model = JSON.parse(await readFile(file, 'utf8'));
35
- }
36
- catch {
37
- issues.push({ message: `Could not read model for '${name}'` });
38
- }
39
- if (isSource && hasIncludes(model))
40
- model = await composedForList(model, file, diagramsDir, issues);
41
- diagrams.push({ name, model, issues, editable });
42
- }
19
+ for (const name of all)
20
+ diagrams.push(await loadEntry(diagramsDir, artifactsDir, name, sourceNames.has(name)));
43
21
  return { status: 200, body: { diagrams } };
44
22
  }
23
+ /** The diagram `name` as the studio's list shows it, or undefined when the list has
24
+ * no such name. Looking the name up in the listing, rather than checking its
25
+ * spelling, is what keeps it inside the two directories: a compiled diagram's name
26
+ * comes from its `.diagram.ts` file and need not pass `isSafeName`. */
27
+ export async function diagramAsShown(diagramsDir, artifactsDir, name) {
28
+ if ((await walkDiagramJson(diagramsDir)).includes(name))
29
+ return loadEntry(diagramsDir, artifactsDir, name, true);
30
+ if ((await walkDiagramJson(artifactsDir)).includes(name))
31
+ return loadEntry(diagramsDir, artifactsDir, name, false);
32
+ return undefined;
33
+ }
34
+ /** One listed diagram: its JSON source with includes expanded, or else its artifact. */
35
+ async function loadEntry(diagramsDir, artifactsDir, name, isSource) {
36
+ // Every read and save refuses a name isSafeName refuses, so such a source is shown but not offered for editing.
37
+ const editable = isSource && isSafeName(name);
38
+ const file = isSource
39
+ ? path.join(diagramsDir, `${name}.diagram.json`)
40
+ : path.join(artifactsDir, `${name}.diagram.json`);
41
+ let model = null;
42
+ const issues = [];
43
+ if (isSource && !editable) {
44
+ issues.push({
45
+ message: `'${name}' is read-only here: the studio saves names of lowercase letters, digits, '-' and '/', none ending in /rename, /eject or /composed. Rename the file to edit it.`,
46
+ });
47
+ }
48
+ try {
49
+ model = JSON.parse(await readFile(file, 'utf8'));
50
+ }
51
+ catch {
52
+ issues.push({ message: `Could not read model for '${name}'` });
53
+ }
54
+ if (isSource && hasIncludes(model))
55
+ model = await composedForList(model, file, diagramsDir, issues);
56
+ return { name, model, issues, editable };
57
+ }
45
58
  /** `model` with its includes expanded for the list, or `model` itself when they
46
59
  * cannot be, with what went wrong added to `issues`. */
47
60
  async function composedForList(model, file, diagramsDir, issues) {
@@ -1,4 +1,5 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { PageSources } from './pages.js';
2
3
  /** The handler module, passed in rather than imported: the Vite adapter loads it
3
4
  * through the dev pipeline, the packaged server imports it directly. */
4
5
  export type Handlers = typeof import('./handlers.js');
@@ -6,6 +7,8 @@ export type Handlers = typeof import('./handlers.js');
6
7
  export interface ApiContext {
7
8
  diagramsDir: string;
8
9
  artifactsDir: string;
10
+ /** what the page route builds from; a host without it answers that route 501 */
11
+ pages?: PageSources;
9
12
  }
10
13
  /** A request in transport-neutral terms: no `IncomingMessage`, so a host with
11
14
  * no HTTP objects at all (the Obsidian in-process bridge) can still drive a
@@ -2,6 +2,7 @@ export { MAX_ASSET_BYTES, readAsset, saveAsset } from './assets.js';
2
2
  export { ejectDiagramSource, listDiagramModels, readComposedDiagram, readDiagram, renameDiagram, saveDiagram, type DiagramEntry, } from './diagrams.js';
3
3
  export { walkDiagramJson, walkFiles } from './files.js';
4
4
  export { readLibrary, saveLibrary } from './library.js';
5
+ export { exportPage } from './pages.js';
5
6
  export type { HandlerResult } from './result.js';
6
7
  export { listDrawings, listLayouts, saveDrawings, saveLayout } from './sidecars.js';
7
8
  export { isSafeName } from '../names.js';
@@ -6,6 +6,7 @@ export { MAX_ASSET_BYTES, readAsset, saveAsset } from './assets.js';
6
6
  export { ejectDiagramSource, listDiagramModels, readComposedDiagram, readDiagram, renameDiagram, saveDiagram, } from './diagrams.js';
7
7
  export { walkDiagramJson, walkFiles } from './files.js';
8
8
  export { readLibrary, saveLibrary } from './library.js';
9
+ export { exportPage } from './pages.js';
9
10
  export { listDrawings, listLayouts, saveDrawings, saveLayout } from './sidecars.js';
10
11
  // The name rule every route checks, for the hosts and tests that reach it here.
11
12
  export { isSafeName } from '../names.js';
@@ -0,0 +1,21 @@
1
+ import { type HandlerResult } from './result.js';
2
+ /** What a host builds a diagram's web page from: the viewer page `publish` stamps
3
+ * models into, and the icon library its `/library/…` pictures are read from. Each
4
+ * host has its own copies (a checkout's build output, a package's `assets/`, the
5
+ * Obsidian plugin's folder), so each says where they are. */
6
+ export interface PageSources {
7
+ shellPath: string;
8
+ libraryDir: string;
9
+ }
10
+ /**
11
+ * The diagram `name` as one self-contained web page: the page `publish` writes for
12
+ * it, built here so the studio can hand it over as a download. The model is the one
13
+ * the studio shows (the saved source, includes expanded, or else the compiled
14
+ * artifact), so the page cannot lag a compile the way an artifact can.
15
+ *
16
+ * Answered as JSON, `{ html, warnings }`, not as raw bytes: what could not be
17
+ * packed in (a missing picture, a malformed drawings sidecar) still leaves a page
18
+ * worth saving, and the studio should say so rather than hand over a quietly
19
+ * broken one.
20
+ */
21
+ export declare function exportPage(diagramsDir: string, artifactsDir: string, sources: PageSources | undefined, name: string): Promise<HandlerResult>;
@@ -0,0 +1,50 @@
1
+ import { access, readFile } from 'node:fs/promises';
2
+ import path from 'node:path';
3
+ import { stampHtml } from '../publish/html.js';
4
+ import { inlineAssets, readSidecars } from '../publish/publish.js';
5
+ import { diagramAsShown } from './diagrams.js';
6
+ import { refuse } from './result.js';
7
+ const existing = async (p) => {
8
+ try {
9
+ await access(p);
10
+ return p;
11
+ }
12
+ catch {
13
+ return undefined;
14
+ }
15
+ };
16
+ /**
17
+ * The diagram `name` as one self-contained web page: the page `publish` writes for
18
+ * it, built here so the studio can hand it over as a download. The model is the one
19
+ * the studio shows (the saved source, includes expanded, or else the compiled
20
+ * artifact), so the page cannot lag a compile the way an artifact can.
21
+ *
22
+ * Answered as JSON, `{ html, warnings }`, not as raw bytes: what could not be
23
+ * packed in (a missing picture, a malformed drawings sidecar) still leaves a page
24
+ * worth saving, and the studio should say so rather than hand over a quietly
25
+ * broken one.
26
+ */
27
+ export async function exportPage(diagramsDir, artifactsDir, sources, name) {
28
+ if (sources === undefined)
29
+ return refuse(501, 'This studio cannot build web pages: its host has no viewer page to build them from.');
30
+ const entry = await diagramAsShown(diagramsDir, artifactsDir, name);
31
+ if (entry === undefined)
32
+ return refuse(404, `No diagram '${name}'`);
33
+ if (entry.model === null)
34
+ return { status: 500, body: { issues: entry.issues } };
35
+ let shell;
36
+ try {
37
+ shell = await readFile(sources.shellPath, 'utf8');
38
+ }
39
+ catch {
40
+ return refuse(500, `No viewer page at ${sources.shellPath} — in a checkout, build it with \`pnpm build:cli\`.`);
41
+ }
42
+ const warnings = [];
43
+ const warn = (line) => void warnings.push(line);
44
+ const sidecar = (suffix) => existing(path.join(diagramsDir, `${name}.${suffix}.json`));
45
+ const [layoutPath, drawingsPath] = await Promise.all([sidecar('layout'), sidecar('drawings')]);
46
+ const sidecars = await readSidecars({ name, layoutPath, drawingsPath }, warn);
47
+ const assets = { libraryDir: sources.libraryDir, assetsDir: path.join(diagramsDir, 'assets'), warn };
48
+ const model = await inlineAssets(entry.model, assets, new Map(), `diagram "${name}"`);
49
+ return { status: 200, body: { html: stampHtml(shell, { model, ...sidecars }), warnings } };
50
+ }
@@ -1,3 +1,4 @@
1
+ import type { PageSources } from './pages.js';
1
2
  type Handlers = typeof import('./handlers.js');
2
3
  /** One route handler's result: handlers' JSON envelope plus readAsset's
3
4
  * optional `bytes`/`contentType`, which the wrapper streams raw. */
@@ -10,6 +11,7 @@ export interface RouteCtx {
10
11
  contentType?: string;
11
12
  diagramsDir: string;
12
13
  artifactsDir: string;
14
+ pages?: PageSources;
13
15
  }
14
16
  export type BodyMode = 'none' | 'json' | 'raw';
15
17
  export interface Route {
@@ -74,6 +74,12 @@ export const ROUTES = [
74
74
  : h.saveDrawings(c.diagramsDir, name, c.body);
75
75
  },
76
76
  },
77
+ // --- pages: a diagram as one self-contained web page, for the studio to download ---
78
+ {
79
+ method: 'GET',
80
+ pattern: /^\/api\/pages\/(.+)$/,
81
+ handler: (h, c) => h.exportPage(c.diagramsDir, c.artifactsDir, c.pages, decodeURIComponent(c.match[1] ?? '')),
82
+ },
77
83
  ];
78
84
  /** The route matching `method` + `url`, or undefined. First match wins. */
79
85
  export function matchRoute(method, url) {
package/dist/cli/io.d.ts CHANGED
@@ -7,6 +7,11 @@ export interface CliIo {
7
7
  err: (line: string) => void;
8
8
  /** text on stdout as it is */
9
9
  write: (text: string) => void;
10
+ /** set when stdout is a terminal, with its width: what a command that draws reads to
11
+ * colour its output and to say when a picture is wider than the screen */
12
+ readonly tty?: {
13
+ columns: number;
14
+ };
10
15
  }
11
16
  /** The process's own streams. `write` is a plain write, which, unlike console.log's, does
12
17
  * not swallow the error of a reader that has closed the pipe. */
package/dist/cli/io.js CHANGED
@@ -4,4 +4,8 @@ export const processIo = {
4
4
  out: (line) => console.log(line),
5
5
  err: (line) => console.error(line),
6
6
  write: (text) => void process.stdout.write(text),
7
+ // read when asked, not at startup: a terminal's width changes with its window
8
+ get tty() {
9
+ return process.stdout.isTTY ? { columns: process.stdout.columns ?? 80 } : undefined;
10
+ },
7
11
  };
@@ -11,6 +11,13 @@ export interface FlagValues {
11
11
  '--agents': true;
12
12
  '--style': string;
13
13
  '--theme': 'light' | 'dark';
14
+ '--plane': string;
15
+ '--layers': string[];
16
+ '--depth': number;
17
+ '--root': string;
18
+ '--ascii': true;
19
+ '--color': true;
20
+ '--no-color': true;
14
21
  }
15
22
  export type Flag = keyof FlagValues;
16
23
  /** What a command takes, as the parser checks it before the command runs. */
package/dist/cli/parse.js CHANGED
@@ -30,6 +30,13 @@ export const STYLE_IDS = [
30
30
  'ascii',
31
31
  'dos',
32
32
  ];
33
+ /** A flag's value that has to be there: no fallback, since a missing value would
34
+ * otherwise swallow the next flag as the value. */
35
+ const required = (flag, hint) => (next) => {
36
+ if (next === undefined || next.startsWith('--'))
37
+ throw badValue(flag, hint);
38
+ return next;
39
+ };
33
40
  /** Every flag, in the order the refusal of one a command does not take goes through them:
34
41
  * how it reads its value, or null for a flag that takes none. */
35
42
  const FLAGS = {
@@ -87,6 +94,24 @@ const FLAGS = {
87
94
  throw badValue('--theme', 'light or dark, e.g. --theme dark');
88
95
  return next;
89
96
  },
97
+ '--plane': required('--plane', 'needs a plane id, e.g. --plane logical'),
98
+ '--layers': (next) => {
99
+ // An empty value is a choice, not a missing one: no layers at all.
100
+ const value = required('--layers', "needs layer ids, e.g. --layers security,data ('' for none)")(next);
101
+ return value
102
+ .split(',')
103
+ .map((id) => id.trim())
104
+ .filter((id) => id !== '');
105
+ },
106
+ '--depth': (next) => {
107
+ if (next === undefined || !/^\d+$/.test(next))
108
+ throw badValue('--depth', 'a whole number of levels to open, e.g. --depth 1');
109
+ return Number(next);
110
+ },
111
+ '--root': required('--root', 'needs a node id, e.g. --root checkout'),
112
+ '--ascii': null,
113
+ '--color': null,
114
+ '--no-color': null,
90
115
  };
91
116
  const isFlag = (arg) => Object.hasOwn(FLAGS, arg);
92
117
  /** Read argv against every flag there is, whichever command it names: which arguments
package/dist/cli/run.js CHANGED
@@ -7,7 +7,9 @@ import { guide } from '../commands/guide.js';
7
7
  import { init } from '../commands/init.js';
8
8
  import { lint } from '../commands/lint.js';
9
9
  import { publish } from '../commands/publish.js';
10
+ import { show } from '../commands/show.js';
10
11
  import { studio } from '../commands/studio.js';
12
+ import { tui } from '../commands/tui.js';
11
13
  import { watch } from '../commands/watch.js';
12
14
  import { findHome, homePaths } from '../home.js';
13
15
  import { resolveInclude } from '../includes.js';
@@ -21,7 +23,9 @@ export const COMMANDS = {
21
23
  lint,
22
24
  watch,
23
25
  publish,
26
+ show,
24
27
  studio,
28
+ tui,
25
29
  eject,
26
30
  diff,
27
31
  guide,
package/dist/cli.js CHANGED
@@ -21,7 +21,7 @@
21
21
  */
22
22
  import { processIo } from './cli/io.js';
23
23
  import { run } from './cli/run.js';
24
- const USAGE = `Usage: diagc <init|compile|lint|watch|publish|studio|eject|diff|guide> [files...] [--out dir]
24
+ const USAGE = `Usage: diagc <init|compile|lint|watch|publish|show|studio|tui|eject|diff|guide> [files...] [--out dir]
25
25
 
26
26
  Commands:
27
27
  init init [name] [--type <type>] [--agents]: set a repository up — a starter
@@ -32,7 +32,11 @@ Commands:
32
32
  lint Report suspicious diagrams (typos, duplicates, unused or undrawn parts); exit 1 on any
33
33
  watch Recompile — and live-recompile — a directory of sources
34
34
  publish Compile and render an HTML/PNG site under .diagrams/
35
+ show show <name>: print the diagram as text — boxes, lines and labels in the
36
+ terminal or a pipe, every container open (--depth folds deeper levels)
35
37
  studio Run the visual studio against the current directory
38
+ tui tui [name]: look at the diagrams in the terminal — fold and unfold,
39
+ go into boxes, switch planes and layers, search; redraws as sources change
36
40
  eject Promote a JSON diagram to a generated TypeScript source (verified)
37
41
  diff diff <from>[..<to>] [names...]: what changed in the diagrams between two git
38
42
  refs (or a ref and the working tree), with before/after pages and PNGs
@@ -47,6 +51,12 @@ Options:
47
51
  --style id Publish: take the PNGs in this style preset (clean, sketch, …) in
48
52
  place of each diagram's own
49
53
  --theme t Publish: take the PNGs light (the default) or dark
54
+ --plane id show: draw this plane (default: the first)
55
+ --layers a,b show: draw these layers in place of the plane's own ('' for none)
56
+ --depth n show: open only the top n levels of containers
57
+ --root id show: draw this container's inside only
58
+ --ascii show: plain ASCII in place of box-drawing characters
59
+ --color, --no-color show: colour or not, whatever stdout is (default: a terminal is)
50
60
  --json lint: print the findings as a JSON array; diff: the changes as JSON
51
61
  --labels a,b diff: name the two sides (default: the refs)
52
62
  --image-url t diff: summary.md's image links as t, {path} standing for each PNG
@@ -65,8 +75,20 @@ async function exit(code) {
65
75
  await Promise.all([process.stdout, process.stderr].map((s) => new Promise((done) => s.write('', done))));
66
76
  process.exit(code);
67
77
  }
78
+ /** A reader that stops early (`diagc show big | head`, quitting `less`) closes the
79
+ * pipe, and what is left to write has nowhere to go. That is the reader's choice, not
80
+ * the command failing: end quietly, as other tools do, rather than with a stack trace. */
81
+ function quietOnClosedPipe(stream) {
82
+ stream.on('error', (e) => {
83
+ if (e.code === 'EPIPE')
84
+ process.exit(0);
85
+ throw e;
86
+ });
87
+ }
68
88
  /** The binary: argv through the process's own streams, then exit with the code. */
69
89
  async function main() {
90
+ quietOnClosedPipe(process.stdout);
91
+ quietOnClosedPipe(process.stderr);
70
92
  return exit(await run(process.argv.slice(2), processIo, USAGE));
71
93
  }
72
94
  void main();
@@ -17,3 +17,7 @@ export declare function diagramNames(io: CliIo, files: readonly string[], known:
17
17
  * says so on stderr, and the pages go out as HTML only. Playwright loads only when a
18
18
  * picture is wanted. */
19
19
  export declare function pngRenderer(io: CliIo, images: boolean): Promise<NonNullable<PublishOptions['renderPng']> | undefined>;
20
+ /** The source a diagram name reads from: its `.diagram.ts`, else its `.diagram.json`;
21
+ * undefined when it has neither. TypeScript first, as the hand-written one of the two
22
+ * (a `.diagram.json` beside it is the studio's, or a leftover from an eject). */
23
+ export declare function sourceOf(name: string, srcDir?: string): string | undefined;
@@ -1,3 +1,5 @@
1
+ import { existsSync } from 'node:fs';
2
+ import path from 'node:path';
1
3
  import { diagramName } from '../names.js';
2
4
  import { RELATIVE_PATHS } from '../paths.js';
3
5
  /** The sources compile and lint read when they are named none. */
@@ -32,3 +34,14 @@ export async function pngRenderer(io, images) {
32
34
  }
33
35
  return snapshot.renderPng;
34
36
  }
37
+ /** The source a diagram name reads from: its `.diagram.ts`, else its `.diagram.json`;
38
+ * undefined when it has neither. TypeScript first, as the hand-written one of the two
39
+ * (a `.diagram.json` beside it is the studio's, or a leftover from an eject). */
40
+ export function sourceOf(name, srcDir = RELATIVE_PATHS.srcDir) {
41
+ for (const ext of ['.diagram.ts', '.diagram.json']) {
42
+ const file = path.posix.join(srcDir, `${name}${ext}`);
43
+ if (existsSync(file))
44
+ return file;
45
+ }
46
+ return undefined;
47
+ }
@@ -0,0 +1,5 @@
1
+ import type { Command } from '../cli/command.js';
2
+ type ShowFlag = '--plane' | '--layers' | '--depth' | '--root' | '--ascii' | '--color' | '--no-color';
3
+ /** `diagc show <name>`: the diagram as text on stdout. */
4
+ export declare const show: Command<ShowFlag>;
5
+ export {};
@@ -0,0 +1,115 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { readFile } from 'node:fs/promises';
3
+ import { buildHierarchy, defined, errMessage, isLayoutOverlay, } from '@diagc/core/internal';
4
+ import { loadModel } from '../compile.js';
5
+ import { diagramName } from '../names.js';
6
+ import { RELATIVE_PATHS } from '../paths.js';
7
+ import { colorModeFor } from '../text/ansi.js';
8
+ import { depthPins, exportPins } from '../text/folds.js';
9
+ import { renderToLines } from '../text/render.js';
10
+ import { cellWidth } from '../text/width.js';
11
+ import { LOCKED, sourceOf } from './shared.js';
12
+ const listOf = (what, ids) => ids.length === 0 ? `it has no ${what}` : `its ${what}: ${ids.join(', ')}`;
13
+ /** What is wrong with the view the flags ask for, or undefined when it can be drawn:
14
+ * a plane, a layer or a root the model does not have, or a root with no inside. */
15
+ function viewProblem(name, model, flags) {
16
+ const plane = flags['--plane'];
17
+ if (plane !== undefined && !model.planes.some((p) => p.id === plane)) {
18
+ return `no plane '${plane}' in ${name}; ${listOf('planes', model.planes.map((p) => p.id))}`;
19
+ }
20
+ const layer = flags['--layers']?.find((id) => !model.layers.some((l) => l.id === id));
21
+ if (layer !== undefined)
22
+ return `no layer '${layer}' in ${name}; ${listOf('layers', model.layers.map((l) => l.id))}`;
23
+ const root = flags['--root'];
24
+ if (root === undefined)
25
+ return undefined;
26
+ const hierarchy = buildHierarchy(model, plane);
27
+ if ((hierarchy.childrenOf.get(root)?.length ?? 0) > 0)
28
+ return undefined;
29
+ const containers = [...hierarchy.childrenOf].filter(([, kids]) => kids.length > 0).map(([id]) => id);
30
+ const which = containers.length === 0 ? ', and it has none' : `: ${containers.join(', ')}`;
31
+ const what = model.nodes.some((n) => n.id === root)
32
+ ? `'${root}' holds nothing to draw`
33
+ : `no node '${root}' in ${name}`;
34
+ return `${what}; --root takes a container${which}`;
35
+ }
36
+ /** The layout beside the source, when there is one that reads as a layout. One that
37
+ * does not is said on stderr and drawn without: the layout only steers the flow. */
38
+ async function readOverlay(source, io) {
39
+ const file = source.replace(/\.diagram\.(ts|json)$/, '.layout.json');
40
+ if (!existsSync(file))
41
+ return undefined;
42
+ try {
43
+ const parsed = JSON.parse(await readFile(file, 'utf8'));
44
+ if (isLayoutOverlay(parsed))
45
+ return parsed;
46
+ }
47
+ catch {
48
+ // reported below, as a layout that does not read
49
+ }
50
+ io.err(`diagc: ignoring ${file}: not a layout file`);
51
+ return undefined;
52
+ }
53
+ const colorFlag = (flags) => flags['--no-color'] === true ? 'no-color' : flags['--color'] === true ? 'color' : undefined;
54
+ /** A terminal wraps a line wider than itself, which takes a picture apart: say so,
55
+ * once, on stderr, where the picture on stdout stays as it is. */
56
+ function widthHint(io, lines, name) {
57
+ if (io.tty === undefined)
58
+ return;
59
+ // eslint-disable-next-line no-control-regex -- the escapes are what is stripped
60
+ const width = Math.max(...lines.map((l) => cellWidth(l.replace(/\x1b\[[0-9;]*m/g, ''))));
61
+ if (width <= io.tty.columns)
62
+ return;
63
+ io.err(`diagc: the picture is ${width} columns wide and the terminal ${io.tty.columns}; pipe it through 'less -S' or use 'diagc tui ${name}'.`);
64
+ }
65
+ /** `diagc show <name>`: the diagram as text on stdout. */
66
+ export const show = {
67
+ flags: ['--plane', '--layers', '--depth', '--root', '--ascii', '--color', '--no-color'],
68
+ positionals: { max: 1, what: 'one diagram name' },
69
+ whyNot: LOCKED,
70
+ async run({ positionals, flags }, { io, usage, home, snapshots }) {
71
+ const name = positionals[0] === undefined ? '' : diagramName(positionals[0]);
72
+ if (name === '' || (flags['--color'] === true && flags['--no-color'] === true)) {
73
+ io.err(name === '' ? 'diagc: show needs a diagram name.' : 'diagc: --color and --no-color contradict each other.');
74
+ io.err(usage);
75
+ return 1;
76
+ }
77
+ const source = sourceOf(name);
78
+ if (source === undefined) {
79
+ io.err(`diagc: no diagram '${name}'`);
80
+ return 1;
81
+ }
82
+ let model;
83
+ try {
84
+ // The source, not its artifact: the picture is of the diagram as it is now,
85
+ // compiled or not, the way lint reads it.
86
+ model = await loadModel(source, {
87
+ rootDir: RELATIVE_PATHS.srcDir,
88
+ coreEntry: home.coreEntry,
89
+ resolver: snapshots.resolver,
90
+ warn: io.err,
91
+ });
92
+ }
93
+ catch (e) {
94
+ io.err(errMessage(e));
95
+ return 1;
96
+ }
97
+ const problem = viewProblem(name, model, flags);
98
+ if (problem !== undefined) {
99
+ io.err(`diagc: ${problem}`);
100
+ return 1;
101
+ }
102
+ const overlay = await readOverlay(source, io);
103
+ const plane = flags['--plane'];
104
+ // A printed picture folds as the PNG does; --depth trades that for the top levels.
105
+ const pins = flags['--depth'] !== undefined ? depthPins(model, plane, flags['--depth']) : exportPins(model, overlay);
106
+ const lines = await renderToLines({ model, pins, ...defined({ overlay, plane, layers: flags['--layers'], root: flags['--root'] }) }, { ascii: flags['--ascii'] === true, color: colorModeFor(process.env, io.tty !== undefined, colorFlag(flags)) });
107
+ if (lines.length === 0) {
108
+ io.err(`diagc: nothing to draw in ${name}`);
109
+ return 0;
110
+ }
111
+ io.write(`${lines.join('\n')}\n`);
112
+ widthHint(io, lines, name);
113
+ return 0;
114
+ },
115
+ };
@@ -0,0 +1,3 @@
1
+ import type { Command } from '../cli/command.js';
2
+ /** `diagc tui [name]`: the diagrams in the terminal, live, until it is quit. */
3
+ export declare const tui: Command<never>;
@@ -0,0 +1,36 @@
1
+ import { mkdir } from 'node:fs/promises';
2
+ import { diagramName } from '../names.js';
3
+ import { RELATIVE_PATHS } from '../paths.js';
4
+ import { screenColorMode } from '../text/ansi.js';
5
+ import { runTui, watchSources } from '../tui/app.js';
6
+ import { processTerminal } from '../tui/terminal.js';
7
+ import { LOCKED, sourceOf } from './shared.js';
8
+ /** `diagc tui [name]`: the diagrams in the terminal, live, until it is quit. */
9
+ export const tui = {
10
+ flags: [],
11
+ positionals: { max: 1, what: 'one diagram name' },
12
+ // Its compile-watch loop resolves includes locked, as the studio's does.
13
+ whyNot: LOCKED,
14
+ async run({ positionals }, { io, home }) {
15
+ const name = positionals[0] === undefined ? undefined : diagramName(positionals[0]);
16
+ if (name !== undefined && sourceOf(name) === undefined) {
17
+ io.err(`diagc: no diagram '${name}'`);
18
+ return 1;
19
+ }
20
+ if (process.stdin.isTTY !== true || process.stdout.isTTY !== true) {
21
+ io.err("diagc: tui needs a terminal; use 'diagc show <name>' to print a diagram.");
22
+ return 1;
23
+ }
24
+ const { srcDir, artifactsDir } = RELATIVE_PATHS;
25
+ await mkdir(srcDir, { recursive: true });
26
+ await runTui({
27
+ terminal: processTerminal(process.stdin, process.stdout),
28
+ srcDir,
29
+ artifactsDir,
30
+ ...(name !== undefined ? { name } : {}),
31
+ watch: watchSources(srcDir, artifactsDir, home.coreEntry),
32
+ color: screenColorMode(process.env),
33
+ });
34
+ return 0;
35
+ },
36
+ };
package/dist/init.d.ts CHANGED
@@ -31,7 +31,7 @@ export declare const AGENTS_END = "<!-- diagc:end -->";
31
31
  /** What `--agents` writes. Commands, not DSL: the guide is where the DSL lives, so
32
32
  * this block does not go stale when the DSL grows. The markers let a later run
33
33
  * replace it in place. */
34
- export declare const AGENTS_BLOCK = "<!-- diagc:begin -->\n## Diagrams\n\nDiagrams live in `.diagrams/src/*.diagram.ts` and are built with `diagc`.\n\n- Run `diagc guide` before writing or changing one; `diagc guide <type>` covers one diagram type.\n- Run `diagc lint --json` until it reports nothing.\n- Run `diagc publish <name>` and look at `.diagrams/static/<name>.png` to check the picture.\n<!-- diagc:end -->\n";
34
+ export declare const AGENTS_BLOCK = "<!-- diagc:begin -->\n## Diagrams\n\nDiagrams live in `.diagrams/src/*.diagram.ts` and are built with `diagc`.\n\n- Run `diagc guide` before writing or changing one; `diagc guide <type>` covers one diagram type.\n- Run `diagc lint --json` until it reports nothing.\n- Run `diagc show <name>` to read the picture as text, and `diagc publish <name>` to look at `.diagrams/static/<name>.png`.\n<!-- diagc:end -->\n";
35
35
  /** Where the skill goes: the folder Claude Code reads a repository's skills from. */
36
36
  export declare const SKILL_PATH = ".claude/skills/diagc/SKILL.md";
37
37
  /** `existing` with `block` added at the end, or — when an earlier block is there —
package/dist/init.js CHANGED
@@ -27,7 +27,7 @@ Diagrams live in \`.diagrams/src/*.diagram.ts\` and are built with \`diagc\`.
27
27
 
28
28
  - Run \`diagc guide\` before writing or changing one; \`diagc guide <type>\` covers one diagram type.
29
29
  - Run \`diagc lint --json\` until it reports nothing.
30
- - Run \`diagc publish <name>\` and look at \`.diagrams/static/<name>.png\` to check the picture.
30
+ - Run \`diagc show <name>\` to read the picture as text, and \`diagc publish <name>\` to look at \`.diagrams/static/<name>.png\`.
31
31
  ${AGENTS_END}
32
32
  `;
33
33
  /** Where the skill goes: the folder Claude Code reads a repository's skills from. */
@@ -1,4 +1,5 @@
1
- import type { DiagramModel } from '@diagc/core/internal';
1
+ import type { DiagramModel, LayoutOverlay, Drawings } from '@diagc/core/internal';
2
+ import { type DiscoveredDiagram } from './discover.js';
2
3
  import type { PictureLook } from './snapshot.js';
3
4
  export interface PublishOptions {
4
5
  srcDir: string;
@@ -34,6 +35,19 @@ export interface PublishResult {
34
35
  * diagram in the warnings for refs it has to leave as they are.
35
36
  */
36
37
  export declare function inlineAssets(model: DiagramModel, opts: Pick<PublishOptions, 'libraryDir' | 'assetsDir' | 'warn'>, cache: Map<string, Buffer>, label: string): Promise<DiagramModel>;
38
+ /** What a page carries beside its model. */
39
+ export interface PageSidecars {
40
+ layout?: LayoutOverlay;
41
+ drawings?: Drawings;
42
+ }
43
+ /**
44
+ * A diagram's layout and drawings as its page carries them; a path left out is a
45
+ * sidecar the diagram does not have. A hand-edited drawings sidecar can be valid
46
+ * JSON and still not be a drawings overlay. Stamping it would put shapeless data
47
+ * into a page that has no validator of its own, so it is warned about and dropped
48
+ * — the page still ships, just without ink. Unparseable JSON throws.
49
+ */
50
+ export declare function readSidecars(d: Pick<DiscoveredDiagram, 'name' | 'layoutPath' | 'drawingsPath'>, warn: (line: string) => void): Promise<PageSidecars>;
37
51
  /** One picture of a diagram: its plane (absent = the first) and what goes between
38
52
  * the diagram's name and `.png`. */
39
53
  export interface PlanePicture {