@diagc/cli 1.8.0 → 1.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.
Files changed (88) hide show
  1. package/README.md +1 -1
  2. package/assets/guide/compose.md +84 -0
  3. package/assets/guide/index.md +9 -1
  4. package/assets/guide/state-machine.md +77 -0
  5. package/assets/skill/SKILL.md +3 -2
  6. package/assets/starters/state-machine/starter.diagram.ts +42 -0
  7. package/assets/studio/assets/index-Cvrj99Nu.js +114 -0
  8. package/assets/studio/assets/index-DyO7mVg-.css +1 -0
  9. package/assets/studio/index.html +2 -2
  10. package/assets/viewer/index.html +35 -33
  11. package/assets/viewer/shared/caveat-cyrillic-500-normal.woff +0 -0
  12. package/assets/viewer/shared/caveat-cyrillic-500-normal.woff2 +0 -0
  13. package/assets/viewer/shared/caveat-cyrillic-700-normal.woff +0 -0
  14. package/assets/viewer/shared/caveat-cyrillic-700-normal.woff2 +0 -0
  15. package/assets/viewer/shared/caveat-cyrillic-ext-500-normal.woff +0 -0
  16. package/assets/viewer/shared/caveat-cyrillic-ext-500-normal.woff2 +0 -0
  17. package/assets/viewer/shared/caveat-cyrillic-ext-700-normal.woff +0 -0
  18. package/assets/viewer/shared/caveat-cyrillic-ext-700-normal.woff2 +0 -0
  19. package/assets/viewer/shared/caveat-latin-500-normal.woff +0 -0
  20. package/assets/viewer/shared/caveat-latin-500-normal.woff2 +0 -0
  21. package/assets/viewer/shared/caveat-latin-700-normal.woff +0 -0
  22. package/assets/viewer/shared/caveat-latin-700-normal.woff2 +0 -0
  23. package/assets/viewer/shared/caveat-latin-ext-500-normal.woff +0 -0
  24. package/assets/viewer/shared/caveat-latin-ext-500-normal.woff2 +0 -0
  25. package/assets/viewer/shared/caveat-latin-ext-700-normal.woff +0 -0
  26. package/assets/viewer/shared/caveat-latin-ext-700-normal.woff2 +0 -0
  27. package/assets/viewer/shared/chakra-petch-latin-500-normal.woff2 +0 -0
  28. package/assets/viewer/shared/chakra-petch-latin-600-normal.woff2 +0 -0
  29. package/assets/viewer/shared/inter-latin-400-normal.woff2 +0 -0
  30. package/assets/viewer/shared/inter-latin-600-normal.woff2 +0 -0
  31. package/assets/viewer/shared/jetbrains-mono-latin-400-normal.woff2 +0 -0
  32. package/assets/viewer/shared/jetbrains-mono-latin-600-normal.woff2 +0 -0
  33. package/assets/viewer/shared/kalam-devanagari-400-normal.woff +0 -0
  34. package/assets/viewer/shared/kalam-devanagari-400-normal.woff2 +0 -0
  35. package/assets/viewer/shared/kalam-devanagari-700-normal.woff +0 -0
  36. package/assets/viewer/shared/kalam-devanagari-700-normal.woff2 +0 -0
  37. package/assets/viewer/shared/kalam-latin-400-normal.woff +0 -0
  38. package/assets/viewer/shared/kalam-latin-400-normal.woff2 +0 -0
  39. package/assets/viewer/shared/kalam-latin-700-normal.woff +0 -0
  40. package/assets/viewer/shared/kalam-latin-700-normal.woff2 +0 -0
  41. package/assets/viewer/shared/kalam-latin-ext-400-normal.woff +0 -0
  42. package/assets/viewer/shared/kalam-latin-ext-400-normal.woff2 +0 -0
  43. package/assets/viewer/shared/kalam-latin-ext-700-normal.woff +0 -0
  44. package/assets/viewer/shared/kalam-latin-ext-700-normal.woff2 +0 -0
  45. package/assets/viewer/shared/viewer.css +2 -0
  46. package/assets/viewer/shared/viewer.js +48 -0
  47. package/dist/api/diagrams.d.ts +20 -0
  48. package/dist/api/diagrams.js +69 -3
  49. package/dist/api/handlers.d.ts +1 -1
  50. package/dist/api/handlers.js +1 -1
  51. package/dist/api/routes.js +13 -0
  52. package/dist/cli/parse.d.ts +1 -0
  53. package/dist/cli/parse.js +1 -0
  54. package/dist/cli.js +2 -0
  55. package/dist/commands/compile.d.ts +1 -1
  56. package/dist/commands/compile.js +5 -6
  57. package/dist/commands/lint.js +4 -5
  58. package/dist/commands/publish.d.ts +1 -1
  59. package/dist/commands/publish.js +15 -7
  60. package/dist/commands/shared.d.ts +9 -0
  61. package/dist/commands/shared.js +30 -1
  62. package/dist/compile.d.ts +11 -1
  63. package/dist/compile.js +25 -6
  64. package/dist/guide.js +23 -10
  65. package/dist/home.d.ts +5 -1
  66. package/dist/home.js +2 -0
  67. package/dist/init.d.ts +1 -1
  68. package/dist/init.js +1 -1
  69. package/dist/lint.js +2 -1
  70. package/dist/loadHints.d.ts +8 -0
  71. package/dist/loadHints.js +36 -0
  72. package/dist/names.js +1 -1
  73. package/dist/publish/html.d.ts +13 -0
  74. package/dist/publish/html.js +54 -2
  75. package/dist/publish/publish.d.ts +10 -0
  76. package/dist/publish/publish.js +45 -23
  77. package/dist/publish/snapshot.d.ts +21 -2
  78. package/dist/publish/snapshot.js +95 -18
  79. package/dist/text/content.js +21 -4
  80. package/dist/text/glyphs.d.ts +8 -0
  81. package/dist/text/glyphs.js +12 -0
  82. package/dist/text/scene.js +1 -1
  83. package/dist/text/vocabulary.js +14 -0
  84. package/dist/tui/details.js +2 -1
  85. package/dist/watch.js +23 -7
  86. package/package.json +2 -2
  87. package/assets/studio/assets/index-CB6jjAka.js +0 -112
  88. package/assets/studio/assets/index-DzVDK5uD.css +0 -1
@@ -0,0 +1,36 @@
1
+ import { didYouMean, ModelBuilder, NodeRef } from '@diagc/core/internal';
2
+ /** The verbs an author reaches for when they want composition and the guide has
3
+ * not told them it is a node option. */
4
+ const COMPOSE_VERBS = new Set(['include', 'includes', 'import', 'compose', 'embed']);
5
+ const COMPOSE_HINT = " — to pull another diagram in, give a node `include`: m.node('part', { include: './part.diagram.json' }); see 'diagc guide compose'";
6
+ /** The author API's method names: what a diagram calls on `m` and on a node handle.
7
+ * The `add*` methods are the builder's own plumbing (NodeRef calls them), so a
8
+ * suggestion never points at one. */
9
+ function authorMethods() {
10
+ const names = new Set();
11
+ for (const proto of [ModelBuilder.prototype, NodeRef.prototype]) {
12
+ for (const name of Object.getOwnPropertyNames(proto)) {
13
+ if (name === 'constructor' || /^add[A-Z]/.test(name))
14
+ continue;
15
+ if (typeof proto[name] === 'function')
16
+ names.add(name);
17
+ }
18
+ }
19
+ return names;
20
+ }
21
+ /**
22
+ * A load error's message with what the author probably meant, when the shape of
23
+ * the message says: `x.y is not a function` is a method that does not exist, so
24
+ * the closest one that does is named, by the lint's own did-you-mean rule — and a
25
+ * composition verb gets told where composition lives instead, since no method is
26
+ * close to what they wanted. Anything else is returned as it is.
27
+ */
28
+ export function loadHint(message) {
29
+ const m = /^(\w+)\.(\w+) is not a function$/.exec(message);
30
+ if (m === null)
31
+ return message;
32
+ const method = m[2];
33
+ if (COMPOSE_VERBS.has(method))
34
+ return `${message}${COMPOSE_HINT}`;
35
+ return `${message}${didYouMean(method, authorMethods())}`;
36
+ }
package/dist/names.js CHANGED
@@ -3,7 +3,7 @@ import { RELATIVE_PATHS } from './paths.js';
3
3
  * (`/api/diagrams/<name>/rename`). A name ending in `/<word>` would be read as
4
4
  * that action on its folder, so it could be created and never saved. Alone, the
5
5
  * word is the plain route's name and is served like any other. */
6
- const ACTION_SEGMENTS = ['rename', 'eject', 'composed'];
6
+ const ACTION_SEGMENTS = ['rename', 'eject', 'composed', 'source'];
7
7
  /** A diagram name the API, the CLI and the file tree all agree on: lowercase
8
8
  * letters, digits and `-`, with `/` between folders, every segment non-empty. */
9
9
  export function isSafeName(name) {
@@ -21,3 +21,16 @@ export declare const SOURCE_NOTICE = "<!--\n Rendered by diagc \u2014 https://g
21
21
  /** Insert the source offer without disturbing the doctype. */
22
22
  export declare function withSourceNotice(shell: string): string;
23
23
  export declare function stampHtml(shell: string, data: unknown): string;
24
+ /** The folder `publish` writes the shared viewer into, beside the pages. No leading
25
+ * underscore or dot: a Jekyll-served Pages branch would drop one, and a diagram is
26
+ * unlikely to take the name. */
27
+ export declare const VIEWER_DIR = "diagc-viewer";
28
+ /** The path a page at `name` (`team/app`) reaches `VIEWER_DIR` by: `../diagc-viewer`. */
29
+ export declare function viewerRelFor(name: string): string;
30
+ /**
31
+ * A page that shares the viewer: the diagram's data inline (a page must open from
32
+ * `file://`, where a fetch is refused), the viewer's stylesheet and script linked
33
+ * from `viewerRel` as classic resources (a module script is refused there too).
34
+ * The head is the single-file shell's, so the two kinds of page open alike.
35
+ */
36
+ export declare function linkedPageHtml(data: unknown, viewerRel: string, title: string): string;
@@ -40,6 +40,58 @@ export function withSourceNotice(shell) {
40
40
  : `${SOURCE_NOTICE}\n${shell}`;
41
41
  }
42
42
  export function stampHtml(shell, data) {
43
- const json = JSON.stringify(data).replace(/</g, '\\u003c');
44
- return withSourceNotice(shell).replace(DG_DATA_SENTINEL, () => json);
43
+ return withSourceNotice(shell).replace(DG_DATA_SENTINEL, () => dataJson(data));
44
+ }
45
+ /** The data as a page carries it: JSON with every `<` escaped, so nothing in a
46
+ * diagram can close the script tag it sits in. */
47
+ const dataJson = (data) => JSON.stringify(data).replace(/</g, '\\u003c');
48
+ /** The folder `publish` writes the shared viewer into, beside the pages. No leading
49
+ * underscore or dot: a Jekyll-served Pages branch would drop one, and a diagram is
50
+ * unlikely to take the name. */
51
+ export const VIEWER_DIR = 'diagc-viewer';
52
+ /** The path a page at `name` (`team/app`) reaches `VIEWER_DIR` by: `../diagc-viewer`. */
53
+ export function viewerRelFor(name) {
54
+ const dir = name.includes('/') ? name.slice(0, name.lastIndexOf('/')) : '';
55
+ const up = dir === '' ? [] : dir.split('/').map(() => '..');
56
+ return up.length === 0 ? `./${VIEWER_DIR}` : `${up.join('/')}/${VIEWER_DIR}`;
57
+ }
58
+ /** The offer for a page that loads the viewer from beside it rather than embedding
59
+ * it: the folder it loads is the same unmodified bundle, so the same address
60
+ * discharges it. Same constraints as SOURCE_NOTICE. */
61
+ const LINKED_SOURCE_NOTICE = `<!--
62
+ Rendered by diagc — ${SOURCE_URL}
63
+
64
+ This page loads the diagc viewer from the ${VIEWER_DIR}/ folder beside it, free
65
+ software under the GNU Affero General Public License, version 3 (AGPL-3.0-only).
66
+ The complete corresponding source of the viewer is available at the address above.
67
+
68
+ The diagram on this page is not covered by that licence. See the additional
69
+ permissions under section 7 in the project's LICENSE file.
70
+ -->`;
71
+ const escapeHtml = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
72
+ /**
73
+ * A page that shares the viewer: the diagram's data inline (a page must open from
74
+ * `file://`, where a fetch is refused), the viewer's stylesheet and script linked
75
+ * from `viewerRel` as classic resources (a module script is refused there too).
76
+ * The head is the single-file shell's, so the two kinds of page open alike.
77
+ */
78
+ export function linkedPageHtml(data, viewerRel, title) {
79
+ return `<!doctype html>
80
+ ${LINKED_SOURCE_NOTICE}
81
+ <html lang="en">
82
+ <head>
83
+ <meta charset="UTF-8">
84
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
85
+ <title>${escapeHtml(title)}</title>
86
+ <meta name="color-scheme" content="light dark">
87
+ <style>html,body,#root{margin:0;height:100%;width:100%}</style>
88
+ <link rel="stylesheet" href="${viewerRel}/viewer.css">
89
+ </head>
90
+ <body>
91
+ <div id="root"></div>
92
+ <script id="dg-data" type="application/json">${dataJson(data)}</script>
93
+ <script src="${viewerRel}/viewer.js"></script>
94
+ </body>
95
+ </html>
96
+ `;
45
97
  }
@@ -6,7 +6,15 @@ export interface PublishOptions {
6
6
  artifactsDir: string;
7
7
  htmlDir: string;
8
8
  staticDir: string;
9
+ /** the single-file viewer page, stamped whole into each page with `singleFile` (and
10
+ * without a `viewerDir`) */
9
11
  shellPath: string;
12
+ /** the built viewer as separate files (`viewer.js`, `viewer.css`, its fonts): copied
13
+ * once into `htmlDir/diagc-viewer/` and loaded by every page from there. Absent, every
14
+ * page carries the shell. */
15
+ viewerDir?: string;
16
+ /** every page whole, viewer and all, as a file to send on its own */
17
+ singleFile?: boolean;
10
18
  libraryDir: string;
11
19
  assetsDir: string;
12
20
  images: boolean;
@@ -27,6 +35,8 @@ export interface PublishResult {
27
35
  gallery: string;
28
36
  /** the diagrams it warned it was skipping, by name */
29
37
  skipped: string[];
38
+ /** the viewer folder the pages load, when they share one */
39
+ viewer?: string;
30
40
  }
31
41
  /**
32
42
  * The model with every image/shape ref it can read swapped for inline data, so
@@ -1,11 +1,11 @@
1
1
  import { existsSync } from 'node:fs';
2
- import { mkdir, readFile, writeFile } from 'node:fs/promises';
2
+ import { cp, mkdir, readFile, writeFile } from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import { errMessage, isDrawings, uniqueSlug } from '@diagc/core/internal';
5
5
  import { classifyAssetRef, rewriteAssetRefs, safeAssetPath } from './assets.js';
6
6
  import { buildGallery } from './gallery.js';
7
7
  import { discoverDiagrams } from './discover.js';
8
- import { stampHtml } from './html.js';
8
+ import { linkedPageHtml, stampHtml, VIEWER_DIR, viewerRelFor } from './html.js';
9
9
  /** The model's display name from its artifact, for a diagram this run did not read. */
10
10
  async function titleOf(modelPath) {
11
11
  try {
@@ -114,12 +114,41 @@ async function renderPictures(name, model, pagePath, run) {
114
114
  }
115
115
  return written;
116
116
  }
117
+ /** One diagram's page: the file written and the model it holds. Throws on what the
118
+ * diagram's own files make impossible, for the caller to report and skip. */
119
+ async function publishPage(d, run) {
120
+ const { opts, warn } = run;
121
+ const model = JSON.parse(await readFile(d.modelPath, 'utf8'));
122
+ const sidecars = await readSidecars(d, warn);
123
+ const inlined = await inlineAssets(model, opts, run.cache, `diagram "${d.name}"`);
124
+ const page = path.join(opts.htmlDir, `${d.name}.html`);
125
+ await mkdir(path.dirname(page), { recursive: true });
126
+ const data = { model: inlined, ...sidecars };
127
+ await writeFile(page, run.shell === undefined ? linkedPageHtml(data, viewerRelFor(d.name), model.name) : stampHtml(run.shell, data));
128
+ return { page, model };
129
+ }
130
+ /** The pictures of a page, when the run takes any; none otherwise. */
131
+ function publishPictures(d, page, model, run) {
132
+ const { opts, warn } = run;
133
+ if (!opts.images || opts.renderPng === undefined)
134
+ return Promise.resolve([]);
135
+ return renderPictures(d.name, model, page, {
136
+ render: opts.renderPng,
137
+ look: opts.look ?? {},
138
+ staticDir: opts.staticDir,
139
+ diagrams: run.discovered,
140
+ warn,
141
+ });
142
+ }
117
143
  export async function publishDiagrams(opts) {
118
144
  const warn = opts.warn ?? console.warn;
119
- const shell = await readFile(opts.shellPath, 'utf8');
120
145
  await mkdir(opts.htmlDir, { recursive: true });
121
146
  if (opts.images)
122
147
  await mkdir(opts.staticDir, { recursive: true });
148
+ // One viewer for every page, or the shell in each: a reader's `file://` open
149
+ // works either way (see linkedPageHtml); what differs is what a site weighs.
150
+ const shared = opts.singleFile !== true && opts.viewerDir !== undefined;
151
+ const shell = shared ? undefined : await readFile(opts.shellPath, 'utf8');
123
152
  const cache = new Map();
124
153
  const all = await discoverDiagrams(opts.artifactsDir, opts.srcDir);
125
154
  const discovered = new Set(all.map((d) => d.name));
@@ -128,36 +157,29 @@ export async function publishDiagrams(opts) {
128
157
  const want = new Set(opts.names);
129
158
  chosen = all.filter((d) => want.has(d.name));
130
159
  }
160
+ // Copied (over) with every run that writes a page, so the pages and the viewer
161
+ // they load are always of one build; a run with nothing to publish leaves none.
162
+ const viewer = shared && chosen.length > 0 ? path.join(opts.htmlDir, VIEWER_DIR) : undefined;
163
+ if (viewer !== undefined)
164
+ await cp(opts.viewerDir, viewer, { recursive: true });
131
165
  const pages = [];
132
166
  const images = [];
133
167
  const skipped = [];
134
168
  // diagram name → the model's display name, for the index cards
135
169
  const titles = new Map();
170
+ const run = { opts, shell, cache, discovered, warn };
136
171
  for (const d of chosen) {
137
172
  try {
138
- const modelRaw = JSON.parse(await readFile(d.modelPath, 'utf8'));
139
- titles.set(d.name, modelRaw.name);
140
- const sidecars = await readSidecars(d, warn);
141
- const inlined = await inlineAssets(modelRaw, opts, cache, `diagram "${d.name}"`);
142
- const pagePath = path.join(opts.htmlDir, `${d.name}.html`);
143
- await mkdir(path.dirname(pagePath), { recursive: true });
144
- await writeFile(pagePath, stampHtml(shell, { model: inlined, ...sidecars }));
145
- pages.push(pagePath);
146
- if (opts.images && opts.renderPng !== undefined) {
147
- const run = {
148
- render: opts.renderPng,
149
- look: opts.look ?? {},
150
- staticDir: opts.staticDir,
151
- diagrams: discovered,
152
- warn,
153
- };
154
- images.push(...(await renderPictures(d.name, modelRaw, pagePath, run)));
155
- }
173
+ // The page counts once written: a picture that then fails skips the diagram
174
+ // (exit 1) but leaves a page a reader can open.
175
+ const { page, model } = await publishPage(d, run);
176
+ titles.set(d.name, model.name);
177
+ pages.push(page);
178
+ images.push(...(await publishPictures(d, page, model, run)));
156
179
  }
157
180
  catch (e) {
158
181
  warn(`publish: skipping diagram "${d.name}": ${errMessage(e)}`);
159
182
  skipped.push(d.name);
160
- continue;
161
183
  }
162
184
  }
163
185
  // A diagram this run published gets a card for the page it wrote now and a thumbnail
@@ -184,5 +206,5 @@ export async function publishDiagrams(opts) {
184
206
  }
185
207
  const galleryPath = path.join(opts.htmlDir, 'index.html');
186
208
  await writeFile(galleryPath, buildGallery(entries, opts.link !== undefined ? { link: opts.link } : {}));
187
- return { pages, images, gallery: galleryPath, skipped };
209
+ return { pages, images, gallery: galleryPath, skipped, ...(viewer !== undefined ? { viewer } : {}) };
188
210
  }
@@ -1,5 +1,24 @@
1
- /** Locate an installed Chrome/Chromium; undefined means "no browser available". */
2
- export declare function findChrome(): string | undefined;
1
+ /** The one line to print when there is no browser: what to do about it, in the
2
+ * order a reader is likely to want. `npx playwright-core install chromium` works
3
+ * wherever diagc is installed, since playwright-core is its dependency. */
4
+ export declare const NO_CHROME_MESSAGE = "No Chrome found \u2014 writing HTML only. Get one with 'npx playwright-core install chromium' (diagc finds it there), set CHROME_PATH, or use --no-images.";
5
+ /** The machine as `findChrome` sees it; every field is the process's own unless a
6
+ * test says otherwise. */
7
+ export interface ChromeSearch {
8
+ env?: NodeJS.ProcessEnv;
9
+ homeDir?: string;
10
+ platform?: NodeJS.Platform;
11
+ /** the places an installer puts a browser (FIXED_CANDIDATES) */
12
+ systemPlaces?: readonly string[];
13
+ }
14
+ /**
15
+ * Locate a Chrome or Chromium; undefined means "no browser available". In order:
16
+ * `CHROME_PATH`, the places an installer puts a browser, then the Chromium that
17
+ * `npx playwright-core install chromium` puts in Playwright's cache — the one
18
+ * command that works on a stock CI runner, so what it installs must be found
19
+ * without a second step.
20
+ */
21
+ export declare function findChrome(search?: ChromeSearch): string | undefined;
3
22
  /** How a picture is taken: which plane (the first when absent), and the look the
4
23
  * publisher chose — a style preset, light or dark — in place of the page's own
5
24
  * (the diagram's style, light). */
@@ -1,22 +1,100 @@
1
- import { existsSync } from 'node:fs';
1
+ import { existsSync, readdirSync, statSync } from 'node:fs';
2
+ import os from 'node:os';
2
3
  import path from 'node:path';
3
4
  import { pathToFileURL } from 'node:url';
4
5
  import { chromium } from 'playwright-core';
5
6
  import { pageSize } from './pageSize.js';
6
- /** Locate an installed Chrome/Chromium; undefined means "no browser available". */
7
- export function findChrome() {
8
- const env = process.env['CHROME_PATH'];
9
- if (env !== undefined && existsSync(env))
10
- return env;
11
- const candidates = [
12
- '/usr/bin/google-chrome',
13
- '/usr/bin/google-chrome-stable',
14
- '/usr/bin/chromium',
15
- '/usr/bin/chromium-browser',
16
- '/snap/bin/chromium',
17
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
18
- ];
19
- return candidates.find((p) => existsSync(p));
7
+ /** The one line to print when there is no browser: what to do about it, in the
8
+ * order a reader is likely to want. `npx playwright-core install chromium` works
9
+ * wherever diagc is installed, since playwright-core is its dependency. */
10
+ export const NO_CHROME_MESSAGE = "No Chrome found — writing HTML only. Get one with 'npx playwright-core install chromium' (diagc finds it there), set CHROME_PATH, or use --no-images.";
11
+ /** The browsers an installation puts on a machine, where `publish` looks before
12
+ * Playwright's own cache. */
13
+ const FIXED_CANDIDATES = [
14
+ '/usr/bin/google-chrome',
15
+ '/usr/bin/google-chrome-stable',
16
+ '/usr/bin/chromium',
17
+ '/usr/bin/chromium-browser',
18
+ '/snap/bin/chromium',
19
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
20
+ ];
21
+ /**
22
+ * Locate a Chrome or Chromium; undefined means "no browser available". In order:
23
+ * `CHROME_PATH`, the places an installer puts a browser, then the Chromium that
24
+ * `npx playwright-core install chromium` puts in Playwright's cache — the one
25
+ * command that works on a stock CI runner, so what it installs must be found
26
+ * without a second step.
27
+ */
28
+ export function findChrome(search = {}) {
29
+ const env = search.env ?? process.env;
30
+ const named = env['CHROME_PATH'];
31
+ if (named !== undefined && existsSync(named))
32
+ return named;
33
+ return ((search.systemPlaces ?? FIXED_CANDIDATES).find((p) => existsSync(p)) ??
34
+ playwrightChromium(env, search.homeDir ?? os.homedir(), search.platform ?? process.platform));
35
+ }
36
+ /** Where Playwright keeps its browsers on this platform, unless `PLAYWRIGHT_BROWSERS_PATH`
37
+ * says otherwise (`0` means beside the package, which diagc does not look into). */
38
+ function playwrightCache(env, homeDir, platform) {
39
+ const named = env['PLAYWRIGHT_BROWSERS_PATH'];
40
+ if (named !== undefined && named !== '')
41
+ return named === '0' ? undefined : named;
42
+ if (platform === 'darwin')
43
+ return path.join(homeDir, 'Library', 'Caches', 'ms-playwright');
44
+ if (platform === 'win32') {
45
+ const local = env['LOCALAPPDATA'];
46
+ return local === undefined ? undefined : path.join(local, 'ms-playwright');
47
+ }
48
+ return path.join(env['XDG_CACHE_HOME'] ?? path.join(homeDir, '.cache'), 'ms-playwright');
49
+ }
50
+ /** The executable a Playwright build folder holds, whatever the layout of that
51
+ * version (`chrome-linux/chrome`, `chrome-mac-arm64/Chromium.app/…`, `chrome-win64/chrome.exe`). */
52
+ const EXECUTABLES = new Set(['chrome', 'chrome.exe', 'headless_shell', 'chrome-headless-shell', 'Chromium']);
53
+ function executableIn(dir, depth = 5) {
54
+ if (depth === 0)
55
+ return undefined;
56
+ let entries;
57
+ try {
58
+ entries = readdirSync(dir);
59
+ }
60
+ catch {
61
+ return undefined;
62
+ }
63
+ for (const entry of entries) {
64
+ const file = path.join(dir, entry);
65
+ let isDir;
66
+ try {
67
+ isDir = statSync(file).isDirectory();
68
+ }
69
+ catch {
70
+ continue;
71
+ }
72
+ if (!isDir && EXECUTABLES.has(entry))
73
+ return file;
74
+ if (isDir) {
75
+ const found = executableIn(file, depth - 1);
76
+ if (found !== undefined)
77
+ return found;
78
+ }
79
+ }
80
+ return undefined;
81
+ }
82
+ /** The newest full Chromium in Playwright's cache, else the newest headless shell. */
83
+ function playwrightChromium(env, homeDir, platform) {
84
+ const cache = playwrightCache(env, homeDir, platform);
85
+ if (cache === undefined || !existsSync(cache))
86
+ return undefined;
87
+ const builds = readdirSync(cache)
88
+ .map((name) => /^(chromium|chromium_headless_shell)-(\d+)$/.exec(name))
89
+ .filter((m) => m !== null)
90
+ // a full browser first, then by build number, newest first
91
+ .sort((a, b) => (a[1] === b[1] ? Number(b[2]) - Number(a[2]) : a[1] === 'chromium' ? -1 : 1));
92
+ for (const build of builds) {
93
+ const found = executableIn(path.join(cache, build[0]));
94
+ if (found !== undefined)
95
+ return found;
96
+ }
97
+ return undefined;
20
98
  }
21
99
  /** Frame padding around the graph, in screen px. */
22
100
  const FRAME_PADDING = 32;
@@ -34,9 +112,8 @@ export function exportUrl(htmlPath, look = {}) {
34
112
  }
35
113
  export async function renderPng(htmlPath, pngPath, look = {}) {
36
114
  const executablePath = findChrome();
37
- if (executablePath === undefined) {
38
- throw new Error('No Chrome found for image export. Install Google Chrome/Chromium, set CHROME_PATH, or run with --no-images.');
39
- }
115
+ if (executablePath === undefined)
116
+ throw new Error(NO_CHROME_MESSAGE);
40
117
  const browser = await chromium.launch({ executablePath, headless: true });
41
118
  try {
42
119
  // Named, not left to the browser: `?export=1` already makes the viewer light (or
@@ -1,4 +1,4 @@
1
- import { ACTIVITY_END_TYPE, FB_EFFECT_TYPE, } from '@diagc/core/internal';
1
+ import { ACTIVITY_END_TYPE, FB_EFFECT_TYPE, SM_DEEP_HISTORY_TYPE, SM_ENTRY_TYPE, SM_EXIT_TYPE, SM_FINAL_TYPE, SM_HISTORY_TYPE, SM_JUNCTION_TYPE, SM_STATE_TYPE, SM_TERMINATE_TYPE, formatTransition, } from '@diagc/core/internal';
2
2
  import { subtitleOf, typeLook } from './vocabulary.js';
3
3
  import { cellWidth, fitCells, printable, wrapCells } from './width.js';
4
4
  /** The cells a name or subtitle wraps at: about what a browser box shows on a line. */
@@ -12,8 +12,21 @@ const TITLE_MAX = 60;
12
12
  export function typeMark(type, shape, glyphs) {
13
13
  if (shape === 'diamond')
14
14
  return glyphs.decision;
15
- if (type === ACTIVITY_END_TYPE)
15
+ if (type === ACTIVITY_END_TYPE || type === SM_FINAL_TYPE)
16
16
  return glyphs.end;
17
+ // these share the rounded shape, so only the type tells them apart
18
+ if (type === SM_HISTORY_TYPE)
19
+ return glyphs.history;
20
+ if (type === SM_DEEP_HISTORY_TYPE)
21
+ return glyphs.deepHistory;
22
+ if (type === SM_ENTRY_TYPE)
23
+ return glyphs.entryPoint;
24
+ if (type === SM_EXIT_TYPE)
25
+ return glyphs.exitPoint;
26
+ if (type === SM_TERMINATE_TYPE)
27
+ return glyphs.terminate;
28
+ if (type === SM_JUNCTION_TYPE)
29
+ return glyphs.junction;
17
30
  // an activity's start, a git commit: the dot is the element, the name a caption
18
31
  if (shape === 'dot')
19
32
  return glyphs.start;
@@ -64,12 +77,16 @@ export function boxText(vn, ctx) {
64
77
  .map((text) => ({ text, role: 'title' }));
65
78
  for (const text of subtitle === '' ? [] : wrapCells(subtitle, NAME_WRAP))
66
79
  lines.push({ text, role: 'subtitle' });
80
+ // a state's behaviours, one line each, cut rather than wrapped: they read as code;
81
+ // only a state lists them, as only a state draws them on the canvas
82
+ const behaviors = (vn.node.type === SM_STATE_TYPE ? (vn.node.behaviors ?? []) : []).map((behavior) => fitCells(printable(formatTransition(behavior)), TITLE_MAX, ctx.glyphs.ellipsis));
83
+ lines.push(...behaviors.map((text) => ({ text, role: 'row' })));
67
84
  const columns = look.shape === 'table' ? (vn.columns ?? vn.node.columns ?? []) : [];
68
85
  lines.push(...columnRows(columns));
69
86
  if (vn.state === 'collapsed')
70
87
  lines.push({ text: `${ctx.glyphs.folded} ${ctx.inside} inside`, role: 'note' });
71
- // a cylinder's lid and a table's rule under its title each take a row
72
- const extra = look.shape === 'cylinder' || columns.length > 0 ? 1 : 0;
88
+ // a cylinder's lid and the rule under a title, above a table's columns or a state's behaviours, each take a row
89
+ const extra = look.shape === 'cylinder' || columns.length > 0 || behaviors.length > 0 ? 1 : 0;
73
90
  return { lines, width: widthOf(lines), height: lines.length + 2 + extra, shape: look.shape, dashed };
74
91
  }
75
92
  /** What an edge says beside its line: the relation's labels, or an aggregate's own
@@ -25,6 +25,14 @@ export interface Glyphs {
25
25
  start: string;
26
26
  end: string;
27
27
  decision: string;
28
+ /** the marks a state machine's history, entry/exit point, terminate and junction start with
29
+ * (a junction is a smaller dot than an initial's `start`) */
30
+ history: string;
31
+ deepHistory: string;
32
+ entryPoint: string;
33
+ exitPoint: string;
34
+ terminate: string;
35
+ junction: string;
28
36
  /** a causal link's delay, after its label */
29
37
  delay: string;
30
38
  }
@@ -61,6 +61,12 @@ export const UNICODE = {
61
61
  start: '●',
62
62
  end: '◉',
63
63
  decision: '◇',
64
+ history: 'H',
65
+ deepHistory: 'H*',
66
+ entryPoint: '○',
67
+ exitPoint: '⊗',
68
+ terminate: '✕',
69
+ junction: '•',
64
70
  delay: '‖',
65
71
  };
66
72
  const ASCII_ROUND = {
@@ -96,5 +102,11 @@ export const ASCII = {
96
102
  start: '*',
97
103
  end: '@',
98
104
  decision: '<>',
105
+ history: 'H',
106
+ deepHistory: 'H*',
107
+ entryPoint: 'o',
108
+ exitPoint: 'x',
109
+ terminate: 'X',
110
+ junction: '.',
99
111
  delay: '||',
100
112
  };
@@ -12,7 +12,7 @@ const DIRECTIONS = new Set(['DOWN', 'UP', 'LEFT', 'RIGHT']);
12
12
  /** The way the plane flows: its saved layout setting, else the model's default. */
13
13
  function directionOf(input) {
14
14
  const saved = input.overlay?.settings?.[layoutPlaneKey(input.model, input.plane)]?.direction;
15
- return saved !== undefined && DIRECTIONS.has(saved) ? saved : defaultLayoutDirection(input.model);
15
+ return saved !== undefined && DIRECTIONS.has(saved) ? saved : defaultLayoutDirection(input.model, input.plane);
16
16
  }
17
17
  /** How the scene is laid out: its plane's flow, and room for DOS's shadows. */
18
18
  const flowOf = (input) => ({
@@ -106,6 +106,19 @@ export const TYPE_LOOKS = {
106
106
  'tm-boundary': box('', { ...dashed, ...open, legend: 'Trust boundary' }),
107
107
  'plan-zone': shaped('rounded', '', { legend: 'Zone' }),
108
108
  'plan-event': shaped('diamond', '', { legend: 'Event' }),
109
+ 'sm-machine': box('', open),
110
+ 'sm-state': shaped('rounded', ''),
111
+ 'sm-region': box('', { ...dashed, ...open }),
112
+ 'sm-initial': shaped('dot', '', { legend: 'Initial state' }),
113
+ 'sm-final': shaped('dot', '', { legend: 'Final state' }),
114
+ 'sm-choice': shaped('diamond', '', { legend: 'Choice' }),
115
+ 'sm-junction': shaped('dot', '', { legend: 'Junction' }),
116
+ 'sm-bar': shaped('bar', '', { legend: 'Fork / join' }),
117
+ 'sm-history': shaped('rounded', '', { legend: 'Shallow history' }),
118
+ 'sm-deep-history': shaped('rounded', '', { legend: 'Deep history' }),
119
+ 'sm-entry': shaped('rounded', '', { legend: 'Entry point' }),
120
+ 'sm-exit': shaped('rounded', '', { legend: 'Exit point' }),
121
+ 'sm-terminate': shaped('rounded', '', { legend: 'Terminate' }),
109
122
  };
110
123
  const solid = { line: 'solid', end: 'arrow' };
111
124
  /** One entry per kind the renderer styles, in its order. */
@@ -130,6 +143,7 @@ export const KIND_LOOKS = {
130
143
  owns: { ...solid, legend: 'Owns' },
131
144
  executes: { ...solid, legend: 'Executes' },
132
145
  checks: { ...solid, legend: 'Checks' },
146
+ transition: { ...solid, legend: 'Transition' },
133
147
  };
134
148
  // What a notation's profile changes (packages/renderer/src/notations.ts). Not pinned
135
149
  // by the test: the profiles are code, not tables, and these are the few looks a
@@ -1,4 +1,4 @@
1
- import { relationLabels } from '@diagc/core/internal';
1
+ import { formatTransition, relationLabels, } from '@diagc/core/internal';
2
2
  import { subtitleOf } from '../text/vocabulary.js';
3
3
  import { cellWidth, printable, wrapCells } from '../text/width.js';
4
4
  // The details panel: what the picture cannot say in a box — the description, every
@@ -44,6 +44,7 @@ export function detailLines(model, id, width, notation) {
44
44
  `id ${id}`,
45
45
  ...(node.description !== undefined ? ['', ...paragraphs(node.description)] : []),
46
46
  ...(parents.length > 0 ? ['', `Inside ${parents.map((p) => nameOf(model, p)).join(', ')}`] : []),
47
+ ...section('Behaviours', (node.behaviors ?? []).map((b) => printable(formatTransition(b)))),
47
48
  ...relations(model, id),
48
49
  ...notes(node),
49
50
  ];
package/dist/watch.js CHANGED
@@ -1,6 +1,8 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { rm } from 'node:fs/promises';
1
3
  import { watch as chokidarWatch } from 'chokidar';
2
4
  import { errMessage } from '@diagc/core/internal';
3
- import { compileFile } from './compile.js';
5
+ import { artifactPathFor, compileFile } from './compile.js';
4
6
  /** Human-readable rendering of a compile event, shared by the one-shot
5
7
  * `compile` command, the `watch` command's live log, and the `studio` watcher
6
8
  * so all three surface success/failure identically. `ok:false` events are
@@ -65,12 +67,25 @@ export function startWatch(dir, outDir, opts = {}) {
65
67
  opts.onEvent?.({ file, ok: false, error: errMessage(e) });
66
68
  }
67
69
  };
68
- // Serialize compiles per file path: each event chains onto the previous
69
- // in-flight compile for the same path, so events for one file are processed
70
- // sequentially in trigger order (a slow earlier compile can no longer report
71
- // or write a stale result after a newer one). Different files still compile
72
- // concurrently.
73
- const runner = createSerialRunner(compile);
70
+ // A source that is gone takes its artifact with it: left behind, the studio
71
+ // would list the diagram again, read-only, from the stale copy. Reported as
72
+ // nothing — there is no result to print.
73
+ const remove = async (file) => {
74
+ try {
75
+ await rm(artifactPathFor(file, outDir, dir), { force: true });
76
+ }
77
+ catch {
78
+ /* a directory already gone, or unreadable: nothing left to remove */
79
+ }
80
+ };
81
+ // Serialize work per file path: each event chains onto the previous in-flight
82
+ // task for the same path, so events for one file are processed sequentially in
83
+ // trigger order (a slow earlier compile can no longer report or write a stale
84
+ // result after a newer one). Different files still compile concurrently. What
85
+ // a task does is decided when it runs, from the disk: a file that is there is
86
+ // compiled, one that is not has its artifact removed — so an add followed by an
87
+ // unlink, or the reverse, lands on whatever the disk says last.
88
+ const runner = createSerialRunner((file) => (existsSync(file) ? compile(file) : remove(file)));
74
89
  const onFsEvent = (file) => {
75
90
  if (!file.endsWith('.diagram.ts') && !file.endsWith('.diagram.json'))
76
91
  return;
@@ -78,6 +93,7 @@ export function startWatch(dir, outDir, opts = {}) {
78
93
  };
79
94
  watcher.on('add', onFsEvent);
80
95
  watcher.on('change', onFsEvent);
96
+ watcher.on('unlink', onFsEvent);
81
97
  return {
82
98
  async close() {
83
99
  await watcher.close();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diagc/cli",
3
- "version": "1.8.0",
3
+ "version": "1.10.0",
4
4
  "description": "Author software-architecture diagrams as code, compile them to a validated model, edit them in a local studio, and publish pages and images.",
5
5
  "license": "AGPL-3.0-only",
6
6
  "author": "Bogdan Frankovskyi",
@@ -45,7 +45,7 @@
45
45
  "fast-glob": "^3.3.0",
46
46
  "jiti": "^2.0.0",
47
47
  "playwright-core": "^1.62.0",
48
- "@diagc/core": "1.8.0"
48
+ "@diagc/core": "1.10.0"
49
49
  },
50
50
  "publishConfig": {
51
51
  "access": "public"