@diagc/cli 1.7.0 → 1.9.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 (93) hide show
  1. package/README.md +1 -1
  2. package/assets/guide/compose.md +84 -0
  3. package/assets/guide/git-graph.md +3 -0
  4. package/assets/guide/index.md +11 -3
  5. package/assets/skill/SKILL.md +2 -1
  6. package/assets/studio/assets/{index-DzVDK5uD.css → index-CAVbaTgv.css} +1 -1
  7. package/assets/studio/assets/index-Cgkqoymm.js +112 -0
  8. package/assets/studio/index.html +2 -2
  9. package/assets/viewer/index.html +23 -23
  10. package/assets/viewer/shared/caveat-cyrillic-500-normal.woff +0 -0
  11. package/assets/viewer/shared/caveat-cyrillic-500-normal.woff2 +0 -0
  12. package/assets/viewer/shared/caveat-cyrillic-700-normal.woff +0 -0
  13. package/assets/viewer/shared/caveat-cyrillic-700-normal.woff2 +0 -0
  14. package/assets/viewer/shared/caveat-cyrillic-ext-500-normal.woff +0 -0
  15. package/assets/viewer/shared/caveat-cyrillic-ext-500-normal.woff2 +0 -0
  16. package/assets/viewer/shared/caveat-cyrillic-ext-700-normal.woff +0 -0
  17. package/assets/viewer/shared/caveat-cyrillic-ext-700-normal.woff2 +0 -0
  18. package/assets/viewer/shared/caveat-latin-500-normal.woff +0 -0
  19. package/assets/viewer/shared/caveat-latin-500-normal.woff2 +0 -0
  20. package/assets/viewer/shared/caveat-latin-700-normal.woff +0 -0
  21. package/assets/viewer/shared/caveat-latin-700-normal.woff2 +0 -0
  22. package/assets/viewer/shared/caveat-latin-ext-500-normal.woff +0 -0
  23. package/assets/viewer/shared/caveat-latin-ext-500-normal.woff2 +0 -0
  24. package/assets/viewer/shared/caveat-latin-ext-700-normal.woff +0 -0
  25. package/assets/viewer/shared/caveat-latin-ext-700-normal.woff2 +0 -0
  26. package/assets/viewer/shared/chakra-petch-latin-500-normal.woff2 +0 -0
  27. package/assets/viewer/shared/chakra-petch-latin-600-normal.woff2 +0 -0
  28. package/assets/viewer/shared/inter-latin-400-normal.woff2 +0 -0
  29. package/assets/viewer/shared/inter-latin-600-normal.woff2 +0 -0
  30. package/assets/viewer/shared/jetbrains-mono-latin-400-normal.woff2 +0 -0
  31. package/assets/viewer/shared/jetbrains-mono-latin-600-normal.woff2 +0 -0
  32. package/assets/viewer/shared/kalam-devanagari-400-normal.woff +0 -0
  33. package/assets/viewer/shared/kalam-devanagari-400-normal.woff2 +0 -0
  34. package/assets/viewer/shared/kalam-devanagari-700-normal.woff +0 -0
  35. package/assets/viewer/shared/kalam-devanagari-700-normal.woff2 +0 -0
  36. package/assets/viewer/shared/kalam-latin-400-normal.woff +0 -0
  37. package/assets/viewer/shared/kalam-latin-400-normal.woff2 +0 -0
  38. package/assets/viewer/shared/kalam-latin-700-normal.woff +0 -0
  39. package/assets/viewer/shared/kalam-latin-700-normal.woff2 +0 -0
  40. package/assets/viewer/shared/kalam-latin-ext-400-normal.woff +0 -0
  41. package/assets/viewer/shared/kalam-latin-ext-400-normal.woff2 +0 -0
  42. package/assets/viewer/shared/kalam-latin-ext-700-normal.woff +0 -0
  43. package/assets/viewer/shared/kalam-latin-ext-700-normal.woff2 +0 -0
  44. package/assets/viewer/shared/viewer.css +2 -0
  45. package/assets/viewer/shared/viewer.js +46 -0
  46. package/dist/api/diagrams.d.ts +20 -0
  47. package/dist/api/diagrams.js +69 -3
  48. package/dist/api/handlers.d.ts +1 -1
  49. package/dist/api/handlers.js +1 -1
  50. package/dist/api/routes.js +13 -0
  51. package/dist/cli/parse.d.ts +9 -1
  52. package/dist/cli/parse.js +14 -1
  53. package/dist/cli/run.js +6 -2
  54. package/dist/cli.js +7 -1
  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/commands/show.d.ts +1 -1
  63. package/dist/commands/show.js +12 -2
  64. package/dist/compile.d.ts +11 -1
  65. package/dist/compile.js +25 -6
  66. package/dist/guide.js +22 -10
  67. package/dist/home.d.ts +5 -1
  68. package/dist/home.js +2 -0
  69. package/dist/init.d.ts +1 -1
  70. package/dist/init.js +1 -1
  71. package/dist/lint.js +2 -1
  72. package/dist/loadHints.d.ts +8 -0
  73. package/dist/loadHints.js +36 -0
  74. package/dist/names.js +1 -1
  75. package/dist/publish/html.d.ts +13 -0
  76. package/dist/publish/html.js +54 -2
  77. package/dist/publish/publish.d.ts +10 -0
  78. package/dist/publish/publish.js +45 -23
  79. package/dist/publish/snapshot.d.ts +21 -2
  80. package/dist/publish/snapshot.js +95 -18
  81. package/dist/text/git.d.ts +52 -0
  82. package/dist/text/git.js +274 -0
  83. package/dist/text/layout.d.ts +29 -0
  84. package/dist/text/paint.js +95 -0
  85. package/dist/text/scene.d.ts +3 -0
  86. package/dist/text/scene.js +7 -3
  87. package/dist/tui/actions.js +14 -2
  88. package/dist/tui/screen.js +1 -0
  89. package/dist/tui/state.d.ts +2 -0
  90. package/dist/tui/state.js +1 -0
  91. package/dist/watch.js +23 -7
  92. package/package.json +2 -2
  93. package/assets/studio/assets/index-DRsUukzt.js +0 -112
package/dist/guide.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
2
  import path from 'node:path';
3
3
  import { NODE_TYPES, NOTATION_NODE_TYPES, NOTATION_RELATION_KINDS, RELATION_KINDS } from '@diagc/core/internal';
4
- import { UnknownStarterError, readStarter } from './starters.js';
4
+ import { UnknownStarterError, readStarter, starterTypes } from './starters.js';
5
5
  const INDEX = 'index';
6
6
  /** `diagc guide all`: the index, then every topic — for a reader who cannot ask
7
7
  * for one (the copy published on the website). */
@@ -62,17 +62,27 @@ function nodeTypesFor(page) {
62
62
  function relationKindsFor(page) {
63
63
  return [...new Set([...RELATION_KINDS, ...notationOwn(NOTATION_RELATION_KINDS, page)])];
64
64
  }
65
- /** One bullet per topic: the command that prints it, and its own title. */
66
- function topicList(guideDir) {
67
- return guideTopics(guideDir)
68
- .map((topic) => {
69
- const file = path.join(guideDir, `${topic}.md`);
65
+ /**
66
+ * One bullet per topic of one kind: the command that prints it, and its own title.
67
+ * A topic with a starter is a diagram type (`init --type` offers it); one without is
68
+ * a feature any diagram can use (composition). Every topic's title is read whatever
69
+ * its kind, so a page with none fails here. `at` names the page the placeholder is in.
70
+ */
71
+ function topicList(ctx, kind, placeholder, at) {
72
+ const types = new Set(starterTypes(ctx.startersDir));
73
+ const bullets = [];
74
+ for (const topic of guideTopics(ctx.guideDir)) {
75
+ const file = path.join(ctx.guideDir, `${topic}.md`);
70
76
  const title = /^# (.+)$/m.exec(readFileSync(file, 'utf8'))?.[1];
71
77
  if (title === undefined)
72
78
  throw new Error(`${file}: a topic starts with a '# Title' line`);
73
- return `- \`diagc guide ${topic}\` — ${title.trim()}`;
74
- })
75
- .join('\n');
79
+ if (types.has(topic) === (kind === 'types'))
80
+ bullets.push(`- \`diagc guide ${topic}\` — ${title.trim()}`);
81
+ }
82
+ if (bullets.length === 0) {
83
+ throw new Error(`${at}: ${placeholder} is empty — ${kind === 'types' ? 'no topic has a starter' : 'every topic has a starter'}`);
84
+ }
85
+ return bullets.join('\n');
76
86
  }
77
87
  /** One page with its placeholders filled. The replacer is a function, so what it
78
88
  * returns is taken literally: a starter holding `$&` or a `{{…}}` of its own is
@@ -97,7 +107,9 @@ function renderPage(page, ctx) {
97
107
  case 'relation-kinds':
98
108
  return codeList(relationKindsFor(page));
99
109
  case 'topics':
100
- return topicList(ctx.guideDir);
110
+ return topicList(ctx, 'types', whole, file);
111
+ case 'feature-topics':
112
+ return topicList(ctx, 'features', whole, file);
101
113
  case 'version':
102
114
  return ctx.version;
103
115
  default:
package/dist/home.d.ts CHANGED
@@ -9,8 +9,12 @@ export type HomeLayout = 'monorepo' | 'packaged';
9
9
  export interface HomePaths {
10
10
  root: string;
11
11
  layout: HomeLayout;
12
- /** single-file viewer HTML that `publish` stamps models into */
12
+ /** single-file viewer HTML that `publish --single-file`, the studio's export and
13
+ * `diff` stamp models into */
13
14
  viewerShell: string;
15
+ /** the same viewer as separate files (`viewer.js`, `viewer.css`, fonts), which
16
+ * `publish` copies once beside the pages for them to share */
17
+ viewerDir: string;
14
18
  /** icon/shape library that `publish` inlines `/library/...` refs from */
15
19
  libraryDir: string;
16
20
  /** module `@diagc/core` is aliased to when jiti executes a `.diagram.ts` */
package/dist/home.js CHANGED
@@ -57,6 +57,7 @@ export function homePaths(home, coreEntry = resolveCoreEntry) {
57
57
  root,
58
58
  layout,
59
59
  viewerShell: path.join(root, 'assets', 'viewer', 'index.html'),
60
+ viewerDir: path.join(root, 'assets', 'viewer', 'shared'),
60
61
  // The studio bundle carries its own `public/library` through the Vite
61
62
  // build, so publish and the studio server read one staged copy.
62
63
  libraryDir: path.join(studioDir, 'library'),
@@ -71,6 +72,7 @@ export function homePaths(home, coreEntry = resolveCoreEntry) {
71
72
  root,
72
73
  layout,
73
74
  viewerShell: path.join(root, 'apps', 'viewer', 'dist', 'index.html'),
75
+ viewerDir: path.join(root, 'apps', 'viewer', 'dist', 'shared'),
74
76
  libraryDir: path.join(root, 'apps', 'studio', 'public', 'library'),
75
77
  coreEntry: path.join(root, 'packages', 'core', 'src', 'index.ts'),
76
78
  studioDir: path.join(root, 'apps', 'studio'),
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 show <name>` to read the picture as text, and `diagc publish <name>` to look at `.diagrams/static/<name>.png`.\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, and `diagc guide compose` pulling other diagrams in.\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
@@ -25,7 +25,7 @@ export const AGENTS_BLOCK = `${AGENTS_BEGIN}
25
25
 
26
26
  Diagrams live in \`.diagrams/src/*.diagram.ts\` and are built with \`diagc\`.
27
27
 
28
- - Run \`diagc guide\` before writing or changing one; \`diagc guide <type>\` covers one diagram type.
28
+ - Run \`diagc guide\` before writing or changing one; \`diagc guide <type>\` covers one diagram type, and \`diagc guide compose\` pulling other diagrams in.
29
29
  - Run \`diagc lint --json\` until it reports nothing.
30
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}
package/dist/lint.js CHANGED
@@ -30,7 +30,8 @@ export async function lintFile(file, opts) {
30
30
  {
31
31
  file,
32
32
  severity: 'error',
33
- code: 'load',
33
+ // a builder refusal names its rule; a source that simply threw is `load`
34
+ code: e.code ?? 'load',
34
35
  message: e.reason,
35
36
  ...(e.line !== undefined && e.column !== undefined ? { line: e.line, column: e.column } : {}),
36
37
  },
@@ -0,0 +1,8 @@
1
+ /**
2
+ * A load error's message with what the author probably meant, when the shape of
3
+ * the message says: `x.y is not a function` is a method that does not exist, so
4
+ * the closest one that does is named, by the lint's own did-you-mean rule — and a
5
+ * composition verb gets told where composition lives instead, since no method is
6
+ * close to what they wanted. Anything else is returned as it is.
7
+ */
8
+ export declare function loadHint(message: string): string;
@@ -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
@@ -0,0 +1,52 @@
1
+ import { type CompiledView, type DiagramModel } from '@diagc/core/internal';
2
+ import type { BoxText } from './content.js';
3
+ import type { TextLayout } from './layout.js';
4
+ /** The graph's spacing across the screen, in cells. */
5
+ export declare const GIT: {
6
+ /** neighbouring columns' distance when nothing needs more: a dot and three cells of line */
7
+ readonly PITCH: 4;
8
+ /** the least room between two tags on one lane: two cells, as one would read the
9
+ * two as one phrase */
10
+ readonly TAG_GAP: 2;
11
+ /** rows from one lane's line to the next: the next lane's tags and a blank row between */
12
+ readonly LANE: 3;
13
+ /** what a stage's frame needs besides its title: a corner and a cell of border
14
+ * before it, a space either side, a cell of border and a corner after */
15
+ readonly FRAME_ROOM: 6;
16
+ /** from the last column's reach to the lanes' names: the tail's run and a space */
17
+ readonly NAME_GAP: 2;
18
+ /** blank rows between the lanes and the boxes under them */
19
+ readonly STRAY_ROW: 1;
20
+ /** between two boxes in that row */
21
+ readonly STRAY_GAP: 4;
22
+ };
23
+ /** The graph's spacing down the screen, in cells. */
24
+ export declare const GIT_DOWN: {
25
+ /** rows from one column's dots to the next when nothing needs more: a dot and the row
26
+ * a branch turns off on, or a merge turns in */
27
+ readonly PITCH: 2;
28
+ /** rows a stage's frame reaches past its first and last dots: the row a line turns
29
+ * on, then its border, so no line turns along a border */
30
+ readonly FRAME: 2;
31
+ /** the least room between a lane's widest tag, or its name, and the next lane */
32
+ readonly LANE_GAP: 2;
33
+ /** columns left of the first lane where stages are framed: the frame's side and a space */
34
+ readonly MARGIN: 2;
35
+ /** what a stage's frame needs past the last lane besides its title: a cell of border
36
+ * before it, a space either side, a cell of border and a corner after */
37
+ readonly TITLE_ROOM: 5;
38
+ /** rows from the last dot's reach to the lanes' names: the tail's run */
39
+ readonly NAME_GAP: 2;
40
+ };
41
+ /** How a git graph is drawn: on which plane, and across the screen or down it. */
42
+ export interface GitWay {
43
+ plane?: string;
44
+ /** across the screen, as the page draws it; absent = down it */
45
+ across?: boolean;
46
+ }
47
+ /**
48
+ * The graph in cells, for a git-graph plane: every node the view shows gets a box — a
49
+ * commit its dot and tag, a lane its name, a stage its frame — and every drawn git
50
+ * link between two dots a route from one to the other.
51
+ */
52
+ export declare function gitCells(model: DiagramModel, view: CompiledView, boxes: ReadonlyMap<string, BoxText>, way: GitWay): TextLayout;